Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter separator in Perl?

Tags:

perl

Function parameters are usually separated by comma(,), but seems also by space in some cases, like print FILEHANDLE 'string'. Why are both of such separators necessary?

like image 234
Thomson Avatar asked Dec 09 '22 02:12

Thomson


2 Answers

print is special builtin Perl function with special syntax rules. Documentation lists four possible invocations:

print FILEHANDLE LIST
print FILEHANDLE
print LIST
print

So while in general function arguments are separated by comma (,), this is an exception that disambiguates print destination from contents to be printed. Another function that exhibit this behavior is system.

Other feature that shares this syntax is called "Indirect Object Notation". The expression in form:

function object arg1, arg2, … angn
#              ^- no comma here

Is equivalent to:

object->function(arg1, arg2, … argn)

So that following statement pairs are equivalent:

$foo = new Bar;
$foo = Bar->new;

The Indirect Object Notation has several problems and generally should be avoided, save for few well-known idioms such as print F "something"

like image 154
el.pescado - нет войне Avatar answered Dec 29 '22 00:12

el.pescado - нет войне


In that example, because print takes a list of arguments and has a default. So you need to tell the difference between printing a scalar, and printing to a filehandle.

The interpreter can tell the difference between:

print $fh "some scalar text";
print $bar, "set to a value ","\n";
print $fh;
print $bar;

But this is rather a special case - most functions don't work like that. I normally suggest for print, that surrounding the filehandle arg in braces differentiates.

You can look at prototypes as a way to get perl to do things with parameters, but I'd also normally suggest that makes for less clear code

like image 23
Sobrique Avatar answered Dec 28 '22 23:12

Sobrique