in reply to Re: Strange behaviour with Arrays and print?
in thread Strange behaviour with Arrays and print?

Hi,

but why is this:

print @fred;

not the same? This prints the elements and not the scalar / count number.

Kind regards,

pingu

Replies are listed 'Best First'.
Re^3: Strange behaviour with Arrays and print?
by johngg (Canon) on Jul 12, 2014 at 13:36 UTC

    Because print takes a list as an argument so @fred is not coerced into scalar context. In your original print @fred."\n" the concatenation coerces scalar context, hence the "10" but if you'd used a comma instead of a full stop then that would have been a list and the elements of @fred would have been printed.

    $ perl -Mstrict -Mwarnings -e ' > my @fred = qw{ one two three }; > print @fred . qq{\n}; > print @fred, qq{\n}; > print qq{@fred\n};' 3 onetwothree one two three

    I hope this makes things clearer.

    Cheers,

    JohnGG

      Got it, thank you! :)
Re^3: Strange behaviour with Arrays and print?
by AnomalousMonk (Archbishop) on Jul 12, 2014 at 13:30 UTC

    Because you are then passing the array  @fred to the function print as an argument list; the array is evaluated in list context and yields its individual elements.

    Update: E.g.:

    c:\@Work\Perl>perl -wMstrict -e "sub foo { print $_[1]; print qq{\n}; ;; my @copy_of_arguments = @_; print $copy_of_arguments[1]; print qq{\n}; } ;; my @ra = qw(one two three); foo(@ra); ;; foo('four', 'five', 'six'); " two two five five
    See  @_ in perlvar.