Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Scalar vs. array context w/ join()

by mdupont (Scribe)
on Nov 14, 2001 at 19:35 UTC ( #125325=perlquestion: print w/replies, xml ) Need Help??
mdupont has asked for the wisdom of the Perl Monks concerning the following question:

Why does this print out the count of the columns?

print OUT join "\t",@{$columns} "\n"; because the join prefers a scalar over an array?

print OUT join ("\t",@{$columns}). "\n";


Title edit by tye after moving out of Obfuscation (was: Not really obfuscation, but.....)

Replies are listed 'Best First'.
(jeffa) Re: Not really obfuscation, but.....
by jeffa (Bishop) on Nov 14, 2001 at 20:43 UTC
    The first line has syntax error, print need's a comma or a period between } and "\n". I think you meant this:
    my $columns = [ qw (one two three) ]; # sample data is GOOD print join "\t",@{$columns}. "\n"; print join ("\t",@{$columns}). "\n";
    I dropped OUT , because it doesn't matter if we are using STDOUT or another handle. So, the first line prints out "3" while the second line prints out the elements of $columns joined by tabs.

    What happened to the first line? Precendance my friend, the dot causes @{$columns} to be evaluated in scalar context, leaving join only one element to well, join: "3\n".

    That's why i like to use a comma instead:

    print join "\t",@{$columns}, "\n";


    (the triplet paradiddle)
      Interesting, I hadn't realized that... This short snippet might illustrate the core issue a bit clearer.
      #!/usr/bin/perl -wT use strict; my @arr = (7,8,9); print ",, => " , @arr , "\n"; # two commas print ",. => " , @arr . "\n"; # comma then dot print "., => " . @arr , "\n"; # dot then comma print ".. => " . @arr . "\n"; # two dots =OUTPUT ,, => 789 ,. => 3 ., => 3 .. => 3


      Note that your final example:

      print join "\t",@{$columns}, "\n";
      ends the output with "\t\n" instead of just "\n". Note much of a "bug" in this case, but a common mistake that can often have more serious effects.     print join("\t",@{$columns}), "\n";

              - tye (but my friends call me "Tye")

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://125325]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (11)
As of 2017-01-24 09:36 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (203 votes). Check out past polls.