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

R paired t test between each row of 3d array
How to better use repeat while loop for indexing and array
MongoDB array duplicates
How to store input from a loop to an array in assembly(mips). How to store the integers I read in arrA?
C assembly error for a given array
Excel Array formula using INDEX and is variable dependant
Filter data from array Angular 2
Writing to an HDF5 file in parallel using chunking in fortran
remove oldest N elements from MongoDB array
How to display array elements in UITextField in swift 3?
Reshape NxNxM array to MxNxN
Adding count to a vector while looping through dataframe
Using arrays to create a set of variables representing the non-blank values of a separate set of variables
How to get all the elements from array of tuples matching String?
Procedure to insert into tables
Accessing instance variables inside an array

Categories

HOME
python
symfony
ssas-2012
jenkins-plugins
redis
project-management
webrtc
fparsec
otrs
rebol
urlencode
docker-windows
jboss-eap-7
jboss7.x
hashicorp-vault
wysiwyg
jacoco
lenskit
pycrypto
multiple-columns
tcpclient
source-maps
visual-c++-2017
metadata-extractor
classpath
owl-api
chrome-native-messaging
gzip
gpib
entity-system
receipt
shibboleth
color-scheme
wsadmin
onbackpressed
exiftool
bing-translator-api
tango
paho
median
estimation
nstouchbar
spring-data-hadoop
mcrypt
fontconfig
teiid
rxvt
autoresize
garrys-mod
inject
windows-azure-pack
try-finally
brython
elastix
mfc-feature-pack
java.util.calendar
rad
retro-computing
futuretask
ytplayerview
web-component-tester
xaml-designer
start-job
c++-actor-framework
microblaze
and-operator
fragment-tab-host
sortable
dto
getimagedata
proxies
initialization-vector
opendata
bigint
xml-libxml
sametime
domain-calculus
enumerators
qsqltablemodel
autostart
text-services-framework
path-manipulation
serp
paintcomponent
open-graph-beta
hadoop-plugins
unreachable-code
filetime
callgrind
lazy-c++
soft-keyboard
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