passing a 2D array.

Hi experts,

I have main.pl and test.pl as follows. In test.pl, there are fun1 and fun2. My fun1 works fine, but my fun2 was not working. Basically, I want both fun1 and fun2 be able to get the array properly. Does anyone know what I missed in fun2? Thanks!

main.pl
----------------------------------------------
#!/usr/bin/perl -w

require "test.pl";

$data[0][0] = 1.0;
$data[0][1] = 11.0;
$data[0][2] = 111.0;

$data[1][0] = 2.0;
$data[1][1] = 22.0;
$data[1][2] = 222.0;

@newData1 = fun1(@data);

print "Test1 "
  . $newData1[1][0] . " "
  . $newData1[1][1] . " "
  . $newData1[1][2];
 
###############################

@newData2 = fun2(@data,2);

print "Test2 "
  . $newData2[1][0] . " "
  . $newData2[1][1] . " "
  . $newData2[1][2];

----------------------------------------

test.pl
---------------
#!/usr/bin/perl -w

sub fun1 {
      @data = @_;

      print "Row Number = " . @data . "\n";
      print "Column Number = " . @{ $data[0] } . "\n";
      print "Data Item [1][1] = " . $data[1][1] . "\n";

      $numRow = @data;
      $numCol = @{ $data[0] };

      for ( $i = 0 ; $i < $numRow ; $i++ ) {
            for ( $j = 0 ; $j < $numCol ; $j++ ) {
                  print $data[$i][$j] . "  ";
            }
            print "\n";
      }
      return @data;

}


sub fun2 {

      @data = @{$_[0]} ;

      print "Row Number = " . @data . "\n";
      print "Column Number = " . @{ $data[0] } . "\n";
      print "Data Item [1][1] = " . $data[1][1] . "\n";

      $numRow = @data;
      $numCol = @{ $data[0] };

      for ( $i = 0 ; $i < $numRow ; $i++ ) {
            for ( $j = 0 ; $j < $numCol ; $j++ ) {
                  print $data[$i][$j] . "  ";
            }
            print "\n";
      }
      return @data;

}
1;

LVL 1
meow00Asked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
@newData2 = fun2(\@data,2);
0
 
meow00Author Commented:
Thanks very much! It works. Now I am just wondering what does the back slash in front of @data mean? Thanks!
0
 
Adam314Connect With a Mentor Commented:
It means pass a reference to the array instead of the array data (kind of like a pointer in C/C++).

Your functions assume that every row will have the same number of columns - although this is the case in the data you have, it's not necessarily true for all 2-D arrays in perl.
0
 
ozoCommented:
perldoc perlref
perldoc perllol
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.