ritesh_NITW ritesh_NITW - 1 year ago 76
Perl Question

Passing array by reference

I have written a simple Perl program (Driver.pl) that passes the

array by reference
and calls the subroutine add in

The calculate.pm module pushes two values 100 and 500 into the array.

When I print the array in Driver.pl file, it prints nothing.

Driver.Pl file:

use calculate;
our @my_array;
sub init() {
$x = 1;
calculate::add($x, /@my_array);
for (@my_array) {
print $_; #Prints Nothing.


sub add() {
my ($x, @arr) = @_;
push (@arr, 100);
push (@arr, 200);

Answer Source

First of all, here is the code you actually want:

File Calculate.pm:

package Calculate;

sub add {
  my ($x, $arrayref) = @_;
  push @$arrayref, 100, 200;


File Driver.pl:

use Calculate;

my @array;

sub init {
  Calculate::add(1, \@array);


foreach (@array) {
  print "$_\n";

What did I do? Well, I fixed all the (syntax-)errors:

  • The reference operator is \ nor /.
  • Loops are for or foreach but never for each. There is an each function that allows us to iterate over collections, but that isn't useful here.
  • Don't use prototypes like (), unless you know exactly what they do, what they mean, and why you have to use them here.
  • Put an explicit package declaration into your library files.

Then there are some severe style issues:

  • Name your packages with uppercase names – lowercase names are reserved for “pragmas”.
  • Declare all variables with my, unless you really need global/dynamic variables. You don't.

And a newline after print can't hurt.

In our add function, we receive an array reference. (If you know C++: Perl references are like pointers, not like C++ references). References are scalars, so we put it into $arrayref. To get the actual array, we dereference it like @$arrayref – but don't do a copy, or you aren't manipulating the original.

You could slurp the remaining arguments into an array, like my ($x, @list) = (1, 2) puts 2 into the array. But in your case, the 2 is an array reference! Therefore the @list contains a single element which is our array reference – but it isn't the same array.

This still isn't elegant code and has architecture problems, but it should now at least compile.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download