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

why is it this doesn't work with a push command?
while(<DATA>) { push @array [$first, $last, $address, $city, $zip]; } foreach (@data){ print $_, "\n"; }

Replies are listed 'Best First'.
Re: push problem
by jryan (Vicar) on Nov 23, 2002 at 01:52 UTC

    You forgot the comma:

    push @array, [$first, $last, $address, $city, $zip];

    By the way, from looking at your printing loop, [] might not do what you expect it to. [] creates an anyonomous array (see perlref), and it won't print anything useful in your loop. To see what I mean, try:

    while(<DATA>) { push @array, [$first, $last, $address, $city, $zip]; } foreach (@array){ print "@$_\n"; }

    You mean have wanted the following, which pushes the elements onto the array linearly:

    push @array, $first, $last, $address, $city, $zip;
Re: push problem
by Bilbo (Pilgrim) on Nov 23, 2002 at 02:00 UTC

    Is this:

    while(<DATA>) { push @array [$first, $last, $address, $city, $zip]; }
    meant to read data from a file?

    You never set the values of $first, $last etc. Assuming that what you mean to do is read 5 values from a file and put the array containing those vlaues in @array then you should do something like:

    while(<DATA>) { push @array, [split]; }

    p.s. are @array and @data supposed to be the same thing?

Re: push problem
by DamnDirtyApe (Curate) on Nov 23, 2002 at 01:54 UTC

    Use strict and warnings; they'll tell you that you're missing the comma after @array (or at least point you in that direction.)

    Update: warnings doesn't actually give you a lot of extra info; use diagnostics for a better explanation.


    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche
      It has nothing to do with strict and warnings; it is a syntax error, it won't even compile.

        Without warnings:

        Type of arg 1 to push must be array (not array slice) at test.pl line +4, near "];" Execution of test.pl aborted due to compilation errors.

        With warnings:

        Useless use of push with no values at test.pl line 4. Type of arg 1 to push must be array (not array slice) at test.pl line +4, near "];" Execution of test.pl aborted due to compilation errors.

        Not a ton of new information, but if you can't figure out what's wrong from the first error message, it might be of some help.


        _______________
        DamnDirtyApe
        Those who know that they are profound strive for clarity. Those who
        would like to seem profound to the crowd strive for obscurity.
                    --Friedrich Nietzsche