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

Hi Monks, Whenever I use a simple push function on an array. i get a space character in front of the elements starting at index 1. Below is an example.
my @array; $i=0; while($i<5) { push(@array,$i); push(@array,"\n"); $i++; } print "@array"; Result : 0 1 2 3 4
Could anyone kindly explain why this is happening and what is the solution to this. Regards, Ravi.

Replies are listed 'Best First'.
Re: Space character when using push function on arrays
by roboticus (Chancellor) on Jul 15, 2010 at 11:13 UTC

    lamravikanth:

    No it doesn't, try this:

    my @array; $i=0; while($i<5) { push(@array,$i); $i++; } print join("|",@array);

    You're getting confused by the stringification of an array. In other words, expanding the array inside a double-quoted string is adding the spaces.

    ...roboticus

Re: Space character when using push function on arrays
by FunkyMonk (Bishop) on Jul 15, 2010 at 11:21 UTC
    Printing "@array" is not the same as printing @array:

    my @array = 1..5; print @array, "\n"; # 12345 print "@array \n"; # 1 2 3 4 5

    Update: Removed a spurious comma. Thanks ikegami

Re: Space character when using push function on arrays
by Anonymous Monk on Jul 15, 2010 at 11:15 UTC
    Because you're interpolating the array, so all the items are joined using the list separator ( see perlvar $")
    @stuff = 1 .. 10; print "@stuff\n"; __END__ 1 2 3 4 5 6 7 8 9 10
Re: Space character when using push function on arrays
by nvivek (Vicar) on Jul 15, 2010 at 12:13 UTC

    You're getting that output because the value $" by default is space.That's why,you're getting 0\n then space which $" is a delimiter and then 1\n followed by space and it continues. If you want to check it,you change the value of $" and check it.You'll understand.To know better about these kind of special variables you refer this URL. http://www.tutorialspoint.com/perl/perl_special_variables.htm

Re: Space character when using push function on arrays
by TedPride (Priest) on Jul 15, 2010 at 19:11 UTC
    my (@arr, $i); for $i (0..4) { push @arr, $i, "\n"; } print join '', @arr;
      Thanks a lot monks, it resolved the issue.