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

I am trying to initialize 3 array's and a scalar in the same line of declaration, but the scalar is always reporting it as undefined.

my (@arr1, @arr2, $var, @arr3) = ( (),(),"0", () );

What could be wrong in this

Replies are listed 'Best First'.
Re: How to declare arrays and scalars together?
by ikegami (Patriarch) on Jun 18, 2012 at 05:17 UTC

    First, ( (),(),"0", () ) is the same as "0".

    Second, no matter what list the right-hand side of the assignment returns, nothing will ever be assigned to $var. Everything will be assigned to @arr1. There's no way for the assignment to know how many elements of the list should be assigned to @arr1, how many to @arr2, etc.

    If you're not assigning anything to more than one array, you can do what you want by moving the scalars to before the arrays.

    my ($var, @arr1, @arr2, @arr3) = "0";
Re: How to declare arrays and scalars together?
by cheekuperl (Monk) on Jun 18, 2012 at 05:18 UTC
    As such, nothing looks/IS wrong in your code. It's just that it does not work the way you are thinking it would.
    my (@arr1, @arr2, $var, @arr3) = ( (1,2),(11,22),"0", () ); print "\n[@arr1]"; print "\nvar is $var";
    RHS of first line is flattened into a single list and copied in its entirety into @arr1.
    All other elements in LHS of first line are empty. Remember why you can not pass multiple arrays to a subroutine?

      "Remember why you can not pass multiple arrays to a subroutine?"

      except, one uses reference like so:

      my $arr1_ref = [ 1, 2, 3 ]; my $arr2_ref = [ 10, 9, 8, 7 ]; load_arr( $arr1_ref, $arr2_ref ); ## load multiple array references sub load_arr { my ( $arr1_def, $arr2_def ) = @_; print join "\n", @{$arr1_def}, @{$arr2_def}; return; }

        You're passing array references there, not arrays.

Re: How to declare arrays and scalars together?
by frozenwithjoy (Priest) on Jun 18, 2012 at 05:28 UTC

    If all you are trying to do is initialize these variables, use:

    my (@arr1, @arr2, $var, @arr3);
      That declares them and initialises them to empty or undef. He wants to initialise $var to zero at the same time.

        Ah yes. I spaced over that part. Too much traveling this weekend! Thanks.

        Note to OP: I recommend using two lines to do what you want to do. For example...

        my ( @arr1, @arr2, @arr3 ); my $var = 0;

        is quite a bit more readable than:

        my ( $var, @arr1, @arr2, @arr3 ) = 0;