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

Read from array1 write from array2
Type Mismatch in Array
Subtracting from each element in array in python
C# Problems importing a file to an array and put each character in it's own index
How to identify the position of a sequence of elements in an array in bash
Combine values of two arrays to form key and values to hash in ruby [duplicate]
Create array with key from dict with sorted by dict values
How do I convert every element in an array to its own array?
Adding a list to an array from different file format in perl
How to use Perl `sort` and `pairwise` if I already have variables `$a` and `$b`
Sum dynamic part of array values Excel VBA
Ada How to get input a list of integer from a user and put it into an array
count occurences in for loop
Update / create subdocument in array
Delphi: const list of const objects [duplicate]
Fastest way to search through a CSV and return specific array of values (Ruby)

Categories

HOME
visual-studio-2015
jenkins-plugins
payment-gateway
filterrific
wildcard
bing
google-sheets-api
cocos2d-x-3.0
jpanel
browserify
websphere-liberty
xcode8.3
hosts
store
glpk
cairo
aptana
ng-show
attask
zoho
ng2-dragula
autolayout
azure-servicebus-queues
bootstrap-typeahead
yosys
croppic
visual-c++-2017
onesignal
image-quality
system.data.sqlite
getjson
graph-databases
pycparser
jquery-cycle2
boilerplate
bing-maps-api
wfp
vmd
s3cmd
soundjs
intellij-idea-2016
taglib
homekit
lftp
python-idle
lumen-5.3
double-buffering
timesten
nsjsonserialization
tuleap
decompress
lotus
cron-task
scalar
nofollow
unsatisfiedlinkerror
multifile-uploader
gherkin
supportmapfragment
geodjango
harp
rspec3
pgm
google-plus-one
candidate-key
errorprovider
snmp4j
suffix-array
java-collections-api
getimagedata
colt
wss
android-json-rpc
chrome-for-android
java.util.date
image-zoom
dllexport
ng-pattern
fieldset
snapjs
domain-calculus
icsharpcode
enumerators
linkedhashset
sunspot-rails
radchart
ninject-extensions
z-machine
objective-c-protocol
nintendo
sendfile
pivotal-crm
requestfactory
task-management
gwt-2.2-celltable
odbc-sql-server-driver
standardized

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