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

Writing an Int-Array to a text file
What is the best way to save/load contents of array to file?
D: Creating an array of templated objects
cURL post json data, json array and image files REST api testing
Tcl array sorting based on values
How do I get all the values from a hash that are in an array?
Get an array dynamicaly from a factory
How to split a string by new lines in Swift
VB.net how to serialize list / array of json objects
How do I convert this hash to an array of hashes?
Define a next_in_line method on Array that takes the element at the beginning of the array and puts it at the end
Best way to calculate means within a MATLAB array based on other values in the array?
Parse the xml array and store the data into array or dictionary using swift
How to select vector elements from each row of a 3D matrix in MATLAB?
How can I locate the element of an array that is nearest to some number? [duplicate]
Fast computation of cumulative sums over four-dimensional arrays in R

Categories

HOME
sharepoint
paypal
swift
admin-on-rest
filterrific
freepascal
wsdl
label
memory-leaks
survival-analysis
transparent
is-empty
webdav
google-plus
octopus-deploy
window
cockroachdb
outlook-web-addins
iso
cortex-a
tee
ejs
bootstrap-popover
bar-chart
phpbb
android-toolbar
jive
sonarqube-msbuild-runner
printdocument
hanami
codelite
bitcoin-testnet
gpib
helix-3d-toolkit
graph-databases
spring-insight
swiftcharts
data-extraction
viewstate
agent
alchemy.js
linq-to-entities
intellij-idea-2016
control-flow-graph
pdftk
paho
powermta
jtds
sapui
sgmlreader
paas
qos
cron-task
elastix
flexjson
xmp
loopj
galaxy
self-hosting
document-oriented-db
eyeql
ninject.web.mvc
js-cookie
twitter-rest-api
bridge
rspec3
activity-streams
cocoascript
dto
author
spdy
codeigniter-a3m
data-generation
config-files
late-static-binding
mbox
unison
flash-cc
visual-c++-2010-express
loop-invariant
facebook-sdk-3.1
nimrod
trimming
jqmobi
ftp4j
backbone-relational
soa-suite
blockingqueue
datarepeater
xmlslurper
gdt
z-machine
jquery-selectbox
path-manipulation
symbol-server
clause
hibernate3-maven-plugin
winverifytrust
webrat
mvvm-foundation
code-design
multibyte-functions
web-statistics
document-library





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