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

#!/usr/bin/perl -w use strict; use CGI ':standard'; my $in = "url"; my $out; print "Content-type: text/html\n\n"; my @newin = split (/\s+/, $in); print "<br>@newin<br>"; my @out = split (/\s+/, $out); print "<br>@out<br>"; @out = push (@out, @newin); print "<br>@out<br>";
gives:
<br>url<br><br><br><br>1<br>
I had expected
<br>url<br><br><br><br>url<br>
reproducing the contents of @newin.

Could someone explain what is happening?

Replies are listed 'Best First'.
Re: pushing arrays gives unexpected result
by Paladin (Vicar) on Feb 10, 2004 at 23:24 UTC
    As the docs for push say:
    push ARRAY,LIST
    
    Treats ARRAY as a stack, and pushes the values of LIST onto
    the end of ARRAY.  The length of ARRAY increases by the
    length of LIST.
    
    *snip*
    
    Returns the new number of elements in the array.
    
    In other words, it modifies the array in place, and returns the number of elements in the, now larger, array. You want to change:
    @out = push (@out, @newin);
    to just:
    push (@out, @newin);
      Seems to be unanimous, then :)

      Thanks all for your time

Re: pushing arrays gives unexpected result
by arden (Curate) on Feb 10, 2004 at 23:28 UTC
    The line @out = push (@out, @newin); is pushing the contents of @newin onto the array @out, then push returns a value of the number of elements now in the array @out. That value is 1 and it gets assigned to @out, replacing the earlier contents.

    If you change the line question to just push (@out, @newin); you will get the results you expect.

Re: pushing arrays gives unexpected result
by Roger (Parson) on Feb 10, 2004 at 23:27 UTC
    In your code,
    @out = push (@out, @newin);
    In your particular example, push (@out, @newin) returns number of elements pushed into @out, which is 1, and then you assign @out = 1;, which is effectively @out = (1). You should remove the @out= part to make it work as expected:
    push @out, @newin;

Re: pushing arrays gives unexpected result
by duff (Parson) on Feb 10, 2004 at 23:25 UTC

    Read the documentation for push. What is its return value?

Re: pushing arrays gives unexpected result
by davido (Cardinal) on Feb 11, 2004 at 05:18 UTC
    Well, everyone else already answered the most urgent problem, but there are a couple other things. If I run your snippet with warnings turned on, it spits out the old uninitialized value warning because you never set $out anywhere prior to executing this line: my @out = split( /\s+/, $out);

    What exactly do you think @out is going to contain, if you're trying to split undef?

    It's often helpful if your boiled down snippets are actually executable code... unless of course the question is "Why won't this execute?". ;)

    Good luck!


    Dave

Re: pushing arrays gives unexpected result
by BUU (Prior) on Feb 11, 2004 at 11:07 UTC
    You could of course just do @out = (@out, @newin);.