jfroebe has asked for the wisdom of the Perl Monks concerning the following question:

Hi

The following code produces the correct array output but the second print occurs after the first print! I don't see why....

#!/usr/bin/perl -w use strict; sub sub_myarray_test; sub sub_myarray_test { my @my_array = ("one", "two", "three"); my @my_array2 = ("four", "five", "six"); print "\n\tIn subroutine \@my_array = @my_array\n"; print "\tIn subroutine \@my_array2 = @my_array2\n\n"; return \(@my_array, @my_array2); } my ($test_array, $test_array2) = sub_myarray_test; print "test_array: @$test_array " . #{${@{$test_array}}} . "\n"; print "test_array2: @$test_array2\n"; exit;
bash-2.05b# test_array

In subroutine @my_array = one two three
In subroutine @my_array2 = four five six

test_array2: four five six

test_array: one two three 1bash-2.05b#

VERSION: Perl 5.8.0 r12 on Gentoo Linux 1.4 (custom)

Any clues?

Thanks

jason

THANKS! That was pretty dumb... and simple... grrr ;-)

Replies are listed 'Best First'.
Re: printing referenced arrays weirdness
by Roger (Parson) on Nov 27, 2003 at 03:25 UTC
    What do you expect the result will be for this?
    print "test_array: @$test_array " . #{${@{$test_array}}} . "\n"; print "test_array2: @$test_array2\n";
    Can you spot the error? Your code is equivalent to this (because of the comment # on the first line) -
    print("test_array: @$test_array " . print "test_array2: @$test_array2 +\n");
    Where your second print is evaluated before the first print.

    If you want to print the index of the last element in the test array, use this ---> $#{@$test_array} instead

Re: printing referenced arrays weirdness
by Anonymous Monk on Nov 27, 2003 at 03:44 UTC
    This is fun.

    The reason your printing is sorta backwards is because you commented out the 'end of line' and you are concatenating the string from the 1st print statement with the second print statement.

    In other words, your code (snippet) (when the comments are removed) looks like:

    print "test_array: @$test_array " . print "test_array2: @$test_array2\ +n";
    Sandy
      To be more specific, both prints are executing, but the first print executes second, since its entire parameter list must be evaluated before it can print. Part of its argument list is the second print function.

      So the 2nd print function executes first. Then the return value of the 2nd print (almost certanly '1') is concatenated to the output of the first print function.

      What a mess huh? lol. Don't worry about it, it's easy to fix, and almost nobody is (wo)man enough to use "cat" to write perfect Perl scripts first time around.


      Dave


      "If I had my life to live over again, I'd be a plumber." -- Albert Einstein