Skip to Content
Perl Hacks
book

Perl Hacks

by Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe
May 2006
Beginner
298 pages
6h 51m
English
O'Reilly Media, Inc.
Content preview from Perl Hacks

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, without parens, before ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Learning Perl 6

Learning Perl 6

brian d foy
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 0596526741Supplemental ContentErrata Page