arrays


Perl: best way to pass array of hash to a sub


My class looks like the below:
package CSVKeepCols;
use strict;
use warnings;
use Text::CSV;
use Data::Dumper;
my $text;
my $del;
my #cols;
my $output = '';
sub load {
my $class = shift;
my $self = {};
bless $self;
return $self;
}
sub input {
my $class = shift;
$text = shift;
return $class;
}
sub setOpts {
my ($class, $opts) = #_;
$del = $opts->{'delimeter'};
#cols = $opts->{'columns'};
}
sub process {
my #lines = split /\n|\r|\n\r|\r\n/, $text;
my $csv = Text::CSV->new({ sep_char => $del });
foreach (#lines) {
die('Invalid CSV data') if !$csv->parse($_);
$output .= __filterFields($csv->fields()) . "\n";
}
}
sub output {
return $output;
}
sub __filterFields {
my #fields = #_;
my $line = '';
foreach (#cols) {
$line .= ',' if $line;
$line .= $fields[$_];
}
return $line;
}
1;
I am using this class from my code like this:
$parser = load CSVKeepCols();
$parser->input($out);
$parser->setOpts({'delimeter' => ',', 'columns' => [1,2]});
$parser->process();
$out = $parser->output();
I am expecting, the setOpts subroutine will take the hash {'delimeter' => ',', 'columns' => [1,2]} and from there it will set the value of $delto , and #cols to (1,2) so that I can loop through the #cols array.
However, when I try to loop through #cols in the __filterFields subroutine I get error
Use of reference "ARRAY(0x22e32e0)" as array index at CSVKeepCols.pm line 52.
How do I fix this?
In setOpts, you set #cols = $opts->{columns};
$opts->{columns} contains a reference to an array ( [1,2] ).
So in __filterFields:
for ( #cols ){
# $_ is an arrayref [1,2]
# you are using it as an index to retrieve a value from #fields
$line .= $fields[$_];
# Thus the error: "use of reference ARRAY"..." as array index"
# You should be using an integer here.
}
To fix it:
sub setOpts {
# ...
# I would prefer checking what was passed in
die "setOpts requires a columns arrayref!"
unless ref($opts->{columns}) && ref($opts->{columns}) eq 'ARRAY';
#cols = #{ $opts->{columns} };
}

Related Links

How do I separate unique and duplicate items from two arrays in perl?
My randomized Array list is not working
Sorting variable-length items / Algorithms
MongoDB : Single update on multiple fields V/S Multiple updates on single field?
Maximum difference between two elements is equal to solve Maximum Subarray?
Create an array from a CSV list
Finding the contents of an Array 'a' after the loop completes
How to replace a single character in a string?
perl find lines containing string 1 then extract character between string 2 and 3
ElasticSearch - why ScriptDocValues returns unique values?
How to loop through output of a command?
Combining multiple arrays into one, indexing sequentially
Printing an array of integers in a collection of buttons, Swift
Passing complex arrays into a function, getting incorrect answer back
How can I create a foreach with a key that has a space in the name?
How do I populate and append a nested array in JSON using golang?

Categories

HOME
symfony
bing
vs-team-services
heap-memory
safari
vlc
recyclerview
phaser-framework
eval
desktop
uiactivityviewcontroller
finite-group-theory
abcpdf
future
off-canvas-menu
google-people
jsonserializer
tortoisegit
excel-2010
facebook4j
header-files
extractor
bcrypt
version-numbering
web-frontend
helper
bitcoin-testnet
websauna
hotmail
threshold
ksoap
npm-publish
code-behind
fax
linq-to-entities
lexical-analysis
code-composer
upsert
z3py
ideone
proof
persistent
shutdown
rollback
date-range
sqlexception
pdfkit
ebtables
c64
manifest.mf
achievements
except
hateoas
hornetq
fabric-twitter
python-winshell
urn
risk-analysis
stream-framework
git-checkout
sqoop2
python-ggplot
slick-2.0
unison
execvp
jqmobi
haskell-platform
apache2.2
shiva3d
vertical-scrolling
abnf
enumerators
mpmovieplayer
gjs
supersized
point-sprites
driving-directions
viewdidload
wchar
serp
gethashcode
symbol-server
getresource
graniteds
pci-bus
method-signature
ajaxpro

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App