-2

Hi I´am trying to learn Perl. I have a problem with creating an array and using references to use it in another subroutine.

Sample code:

#!/usr/bin/perl

use strict;
use warnings;

sub test {

  my @a = ("a","b","c");

  return \@a;
}

# code just for test, the reference would just be used in next subroutine
my $array = test();
my @arr   = @array;

print "@arr\n"; # just for test

test2(@arr);

sub test2 {

  my @array1 = @_;

  foreach $values (@array1) {
    # do things
  }
}

The point is to use the array from the 1st sub in the second one.

----------------- V2 -------------------------

#!/usr/bin/perl

    use strict;
    use warnings;
    test();
    sub test {

      my @a = ("a","b","c");

      return \@a;
    }

    print "\@a\n";

    test2(\@a);

    sub test2 { (my $array1) = @_;
      foreach my $values (@array1) {
        print "$values\n";
      }
    }
  • 3
    `my @ =` is a syntax error. – melpomene Apr 11 '17 at 07:19
  • The fact that you have included the syntax error `my @ =` indicates that you haven't pasted in the actual code that you have tested. That means that we can't trust anything else in your question. It looks like the problem is the confusion between `@array` and `$array` - but that could just be a typo. It's disrespectful to ask us to debug code that you haven't even run. – Dave Cross Apr 11 '17 at 13:25
  • On further investigation, I notice that this code also fails to run because you have `use strict` but you don't declare `@array`. So running this program will die with a fatal error. At this point it seems that you don't really care about getting a solution to this problem, and I'm moving on to help someone else. – Dave Cross Apr 11 '17 at 13:28
  • sorry for that Dave, just a typo. Running the code on a VM without GUI so could copy past it. – DragonRapide Apr 11 '17 at 14:29

1 Answers1

1

@array is a completely different variable from $array. To dereference $array, use @$array (see http://perlmonks.org/?node=References+quick+reference).

And it would be more efficient to just pass the reference to test2, so:

test2($array);
sub test2 {
    my ($array1) = @_;
    foreach $values (@$array1) {
ysth
  • 96,171
  • 6
  • 121
  • 214