Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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";

mdupont

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

Comment on Scalar vs. array context w/ join()
Select or Download Code
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";

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (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

      -Blake

      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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://125325]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2015-07-08 01:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls