Hack #89. Invoke Functions in Odd Ways

Hide function calls behind familiar syntax.

Everyone's familiar with the normal ways to invoke Perl functions: foo( ) or foo(someparams...) or, in the case of method calls, class->foo(...) or $obj->foo(...).

The Hack

There are far stranger ways to invoke a function. All of these ways are usually too weird for normal use, but useful only on occasion. That's another way[4] to say that they are the perfect hack.

Make a Bareword invoke a function

If you have a function named foo, Perl will let you call it without parens as long as it has seen the function defined (or predefined) by the time it sees the call. That is, if you have:

sub foo
{
    ...a bunch of code....
}

or even just:

sub foo;   # predefine 'foo'

then later in your code you are free to write foo($x,$y,$z) as foo $x,$y,$z. A degenerate case of this is that if you have defined foo as taking no parameters, with the prototype syntax,[5] like so:

sub foo ( )
{
    ...a bunch of code...
}

or:

sub foo ( );

then you can write foo( ) as just plain foo! Incidentally, the constant pragma prior to Perl 5.9.3 defines constants this way. The Perl time( ) function (very non-constant) also uses this approach—that's why either of these syntaxes mean the same thing:

my $x = time;
my $x = time( );

You could implement a function that returns time( ) except as a figure in days instead of in seconds:

sub time_days ( )
{
    return time( ) / (24 * 60 * 60);
}

my $xd = time_days;

If you tried calling time_days ...

Get Perl Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.