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

What's the easiest way to create a case class objects from an Array of Tuple2?
How much faster is implicit expansion compared with bsxfun?
Hash with array in value
How to get the length of a report's GroupingLevel array in VBA
Q2: AttributeError: 'builtin_function_or_method' object has no attribute 'size'
How can I make the following code into a 2D array?
How to write from an array to another array in excel vba
How to store variables from loop to a file
Add a new value to array
Segmentation fault with array indexing in Fortran
Printing a ruby array with zero formatting
how to store a list in a single array index
Minizinc: create an array of int pairs
Given an array of integers, where every number appears thrice except one number appears twice, find the number that appears twice?
How to match value against array and set variables?
Empty array using scan functrion ruby

Categories

HOME
pug
ibm-watson-cognitive
erlang
project-management
textwatcher
laravel-5.3
aem
rocketmq
webdav
tizen-wearable-sdk
vsftpd
requirejs
onenote-api
eclipse-cdt
uiactivityviewcontroller
flexbox
window
wicket
xlsx
cross-platform
mule-studio
atlassian-plugin-sdk
primes
ios10.3
distance
jni
sonarqube-msbuild-runner
flexboxgrid
deb
bootstrap-typeahead
searchbar
croppic
kong
fetch-api
superscript
gpib
crt
oracle-xml-db
division
node-horseman
rhino
large-data
nunit-3.0
deepstream.io
delphi-10.1-berlin
polyfills
onbackpressed
aqgridview
collapsingtoolbarlayout
gmt
shinyjs
pdflib
picasa
freetype2
dojox.charting
image-editing
distribute
handlebars.java
datainputstream
function-fitting
abas
wif
team-build
type-mismatch
divide-by-zero
viper-architecture
twitter-rest-api
uos
adobe-indesign
scrollspy
guzzle6
subversion-edge
jython-2.7
proximity
odftoolkit
x-ua-compatible
outline
facebook-wall
power-law
emma
spdy
picat
ifft
slick-2.0
visualstatemanager
cling
confusion-matrix
installshield-2009
execvp
dwolla
qss
magickwand
cgpath
pys60
crocodoc
blockingqueue
tfs-power-tools
responsetext
nssavepanel
windows-live-id
.app
requestfactory
idictionary
webrat
multibyte-functions
graph-layout
lazy-c++
weborb
interface-design
visual-studio-dbpro
cots





Mobile Apps Dev
Database Users
javascript
java
csharp
php
android


MS Developer
developer works
python
ios
c
html
jquery


RDBMS discuss