Reputation: 3457
I'm trying to figure out why these two lines produce different results:
print($fh, "text"); --> 0x10101010 text (on STDOUT)
print($fh "text"); --> text (inside of file $fh)
When I have the comma I understand I create a list and when print only has a list it prints the list to STDOUT. But, what is print doing when I don't have a comma? The result I want is the one I get without a comma.
This is strange to me and counters me expecting the one with the comma to work for my intended purpose. Code I usually see does filehandle printing with a line like "print $file "text"
", but I want to use the parentheses as I find that more consistent with other languages. But, not putting a comma is just as inconsistent.
An explanation of the internals of "print" might help me understand. How is it getting the FILEHANDLE and LIST separate when there is no comma?
Docs: http://perldoc.perl.org/functions/print.html
Thanks!
Upvotes: 1
Views: 372
Reputation: 57640
In Perl, parens are mostly just used for precedence. It is customary to call builtins like print
without parens – this emphasizes that they aren't subroutines, but special syntax like for
, map
, split
, or my
.
In your case, you have a variety of possibilities:
Leave out the comma, but this is error-prone:
print($fh @list);
print $fh (@list);
Use curly braces around the file handle (which I would suggest anyway):
print { $fh } (@list);
print({ $fh } @list);
Use the object-oriented interface:
use IO::File; # on older perls
$fh->print(@list);
Upvotes: 3
Reputation: 93765
print
isn't a normal function, and you shouldn't call it with the parentheses because you're not really passing a parameter list to the function.
The way I typically it written is
print {$fh} 'text';
print {$fh} 'text1', 'text2';
or not going to a file:
print 'text';
print 'text1', 'text2';
You ask "How is it getting the FILEHANDLE and LIST separate when there is no comma?" and the answer is "Magic, because it's not a normal function."
Upvotes: 5