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 to display this data in twig
How to properly parse a dictionary array
Sort array [[String: Any]] alphabetically in swift 3.0 [duplicate]
In Ruby, how do I execute “select_with_index” on an array?
Is it possible to turn an array to a Result<> in Realm?
MongoDB resolve each ObjectId in an array field to an object from another collection
Play framework, parse json array from request
Swift array of Generics with protocols [duplicate]
How to reverse a given array of numbers in Python 3?
Saving an array of Integers using UserDefaults
delphi Send a file as byte array to a Rest service
Most frequent element in an array (bash 3.2)
User defined function changing each value in an array
swift vapor json response to array
Mongodb inserting into nested array of objects
Spaces in array content getting broken with grep

Categories

HOME
google-apps-script
sql-server
symfony
admin-on-rest
elixir
shopify
scipy
system-verilog
hana
laravel-4
phonegap-cli
shader
octopus-deploy
symfony-forms
webmethods
future
jpeg2000
zend-framework-mvc
styles
tweets
uiautomator
autolayout
os161
cep
forum
invoke-command
twitter-bootstrap-2
freebase
npm-shrinkwrap
precedence
zero
fltk
nsexception
ical-dotnet
sendgrid-templates
rich-text-editor
encapsulation
data-integration
ti-basic
gist
jenkins-jira-trigger
applepayjs
component-pascal
info
static-code-analysis
qos
objloader
inject
push-diffusion
galleriffic
audioqueue
unsatisfiedlinkerror
clob
selecteditem
proxygen
mfc-feature-pack
evo
rad
ipojo
on-duplicate-key
leadtools-sdk
graphical-logo
lines-of-code
isml
xaml-designer
stackframe
start-job
grunt-express
cppdepend
json-patch
dynamic-proxy
bignum
ruboto
pep8
qtgui
graph-coloring
cbcentralmanager
moq-3
deploying
coff
testunit
adsl
port-scanning
ihttphandler
search-path
adobe-contribute
msn
clients
scala-2.8
savestate
integer-promotion
internals
odbc-sql-server-driver
castle-validators
weborb
document-library

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