What is the difference between
my @a = (1) x 1024; print $_, "\n" for @a;
and
my @b = (1) x 1024; print "$_\n" for @b;
Answer:
About 14kb:
#!/usr/bin/perl use strict; use warnings; use Devel::Size 'total_size'; my @a = (1) x 1024; my @b = (1) x 1024; open my $fh, "> /dev/null" or die; print $fh $_, "\n" for @a; print $fh "$_\n" for @b; close $fh; print total_size(\@a), "\n"; print total_size(\@b), "\n"; __END__ 24636 38972
That's because the "$_\n" causes stringification, and the $_, "\n" doesn't.

Replies are listed 'Best First'.
Re: print "$var\n" or print $var, "\n"
by Mr. Muskrat (Canon) on Feb 17, 2005 at 13:06 UTC

    The difference is in the magic that makes Perl, well, Perl.

    Scalars can be numeric or "strings". When you store an integer in a scalar it's stored as an IV. When you use that scalar in string context it gets stringified. The scalar is modified behind the scenes to be a PVIV with pointers to an IV and PV.

    #!/usr/bin/perl use strict; use warnings; use Devel::Peek; my @a = (1) x 1024; my @b = (1) x 1024; open my $fh, "> /dev/null" or die; print $fh $_, "\n" for @a; print $fh "$_\n" for @b; close $fh; Dump $a[0]; Dump $b[0];

    Update: Fixed wording of fourth sentence.

Re: print "$var\n" or print $var, "\n"
by kscaldef (Pilgrim) on Feb 17, 2005 at 17:59 UTC
    Another difference: "$_\n" will always DWYW. However, if some naughty person modified $, then $_,"\n" might do something unexpected.

      Unless of course someone's mucked with $\ . . .

      $ perl -le '$\="wubba\n"; print "foo\n"' foo wubba

      Update: Good point about printf below. There's also syswrite, for that matter.

        A 'fix' for that: printf :)

        You can always localize it if you're afraid of ghosts.

        Makeshifts last the longest.

Re: print "$var\n" or print $var, "\n"
by davido (Cardinal) on Feb 17, 2005 at 17:02 UTC

    :) Of course it depends on what you call a "difference". From another perspective, the difference is: ','

    It all depends on how you look at the world.


    Dave