in reply to Strange behaviour with Arrays and print?

Perl sees your last line as

print( (@fred."\n") );

... that is, it first evaluates @fred . "\n" and then prints that result.

. evaluates its operands in scalar context. An array in scalar context evaluates to the number of its elements. Your expression then becomes

print( (scalar(@fred),"\n") );

... which is

print 10,"\n";

If you want to print an array, maybe put it in string context first:

print "@fred\n";

Replies are listed 'Best First'.
Re^2: Strange behaviour with Arrays and print?
by CountZero (Bishop) on Jul 12, 2014 at 13:04 UTC
    or use say instead of print, then you don't have to append a "\n".

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re^2: Strange behaviour with Arrays and print?
by pingufreak83 (Initiate) on Jul 12, 2014 at 13:20 UTC
    Hi,

    but why is this:

    print @fred;

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

    Kind regards,

    pingu

      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! :)

      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.