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

Powershell, Start-Job is not Working. Without Start-job script is Ok
Correctness of algorithm to find maximum in array
Using smart pointers for array
Why another array is replaced in julia?
Cannot plot a 2D array using contourf()
Efficient way of doing numerical integration on a 2d array with variable integration length
Reshape in Fortran90
Using any array
How to pass array to nsuserdefaults and use them in a section in tableview
Extract value from const array in Z3
How do you use the buffer? [intel based assembly]
Is there a built-in function in MATLAB to get bsxfun(#rdivide,abs(X),sum(abs(X)))?
Array does not work on Powershell 2.0
Iterate through array of hashes in ANT script
To optimize use of memory is it required to clear Array Data
Converting string array to float array

Categories

HOME
mql4
erlang
signalr
vb6
ncurses
phpstorm
couchdb-2.0
safari
rebol
dataframe
apiconnect
ng-admin
ndis
hashicorp-vault
game-maker-studio-1.4
uiscrollview
cratedb
jquery-terminal
tree-traversal
internet-explorer-8
google-api-java-client
google-ima
profile
jquery-waypoints
printdocument
katharsis
rhmap
autofill
strophe
outsystems
data-extraction
mapguide
vmd
image-compression
fltk
ddms
viewgroup
email-parsing
openweathermap
aqgridview
nsjsonserialization
ti-basic
istorage
webdatagrid
iphone-developer-program
emoticons
gmt
bettercms
spyne
garrys-mod
project-template
nsfetchedresultscontrolle
ebtables
iostat
tomee
rmongodb
picasa
radians
multilingual-app-toolkit
squirrel
emokit
direct3d12
jenkins-scriptler
android-snackbar
ipojo
risk-analysis
jazz
hiera
ticket-system
ctrlp
candidate-key
tcpreplay
ember-addon
korma
ssms-addin
mbox
sqljdbc
goinstant
dig
justgage
adomd.net
mailcore
zend-lucene
reporting-tools
vt100
phpsh
usn
xgettext
hashalgorithm
electronic-signature
newsstand-kit
dcpu-16
out-of-browser
surefire
external-assemblies
weborb
dotproject

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