perl - Passing array by reference -
i have written simple perl program (driver.pl) passes array reference
, calls subroutine add in calculate.pm
module.
the calculate.pm module pushes 2 values 100 , 500 array.
when print array in driver.pl file, prints nothing.
driver.pl file:
use calculate; our @my_array; sub init() { $x = 1; calculate::add($x, /@my_array); } init(); (@my_array) { print $_; #prints nothing. }
calculate.pm
sub add() { ($x, @arr) = @_; push (@arr, 100); push (@arr, 200); } 1;
first of all, here code want:
file calculate.pm
:
package calculate; sub add { ($x, $arrayref) = @_; push @$arrayref, 100, 200; } 1;
file driver.pl
:
use calculate; @array; sub init { calculate::add(1, \@array); } init(); foreach (@array) { print "$_\n"; }
what did do? well, fixed (syntax-)errors:
- the reference operator
\
nor/
. - loops
for
orforeach
neverfor each
. thereeach
function allows iterate on collections, isn't useful here. - don't use prototypes
()
, unless know exactly do, mean, , why have use them here. - put explicit package declaration library files.
then there severe style issues:
- name packages uppercase names – lowercase names reserved “pragmas”.
- declare variables
my
, unless need global/dynamic variables. don't.
and newline after print
can't hurt.
in our add
function, receive array reference. (if know c++: perl references pointers, not c++ references). references scalars, put $arrayref
. actual array, dereference @$arrayref
– don't copy, or aren't manipulating original.
you slurp remaining arguments array, my ($x, @list) = (1, 2)
puts 2
array. in case, 2
array reference! therefore @list
contains single element our array reference – isn't same array.
this still isn't elegant code , has architecture problems, should @ least compile.
Comments
Post a Comment