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

Sum of matrices in 3-dimensional object of variable dimesions without looping
Quickly select arrays which have at least k elements common with master array
In Swift, how efficient is it to append an array?
How to correctly split a signal in matlab?
Accessing array of numbers in ARM (with Komodo compilation)
Load, show, convert image from byte array (database) in Windows Phone 8.1
Assembly - Copying an array of bytes - MIPS
Deep Query using MongoDB
plot array from matrix matlab [closed]
Function similar to head() in Matlab
Matlab, Symbolic functions,
R .Fortran return reshaped array?
Array in Powershell WON'T be written as an Array
Converting a graph structure to a 2d array
convert Array to object Angularjs [closed]
Finding whether there are two coprime numbers in an array

Categories

HOME
cluster-computing
nlp
wsdl
json-ld
sbt-assembly
rfc
histogrammar
schemacrawler
spring-cloud-contract
nodemailer
xcode8.3
click
nixos
jacoco
pdo
propel2
cython
autolayout
kitematic
servicemix
tarantool
binutils
pcre
weinre
pycparser
passenger
pace
bigcartel
haskell-pipes
fax
android-maps-v2
intersystems-ensemble
median
openweathermap
lirc
w3-total-cache
chown
gulp-typescript
chessboard.js
vst
inotifypropertychanged
dbscan
gradle-release-plugin
logcat
git-rebase
loopj
test-class
hornetq
sourcegear-vault
evo
oai
rx-groovy
sparse-file
mdm-zinc
ember-cli-addons
robocode
cloudpebble
smartystreets
phpdocx
voldemort
xenocode
json-patch
edit-in-place
winrt-httpclient
facebook-chat
windows-mobile-6
robospice
javascriptmvc
ruboto
manage.py
cgpath
crocodoc
returnurl
redirectstandardoutput
maven-ant-tasks
v4l
ajax.beginform
ou
smooth
ihttphandler
ruby-debug
nagle
nvelocity
zend-form-element
getresource
chdatastructures
act
method-signature
interface-design
divx

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