Back to Top

Wednesday, March 25, 2009

Function references in Perl

A friend asked me how to do the following:


use strict;
use warnings;
use File::Copy 'move';

my $op = $condition ? \&move : \&link;
# ...
$op->($a, $b);

So, I tried to get it working, but I kept getting the error:

Undefined subroutine &main::link called at linkme.pl line 2.

For move it worked fine. Finally, thanks to the guys and girls on #perl from freenode.net I found the following documentation: perlsub - Overriding Built-in Functions. Amongst other useful things it says that:

Even though it looks like a regular function call, it isn't: you can't take a reference to it, such as the incorrect \&CORE::open might appear to produce.

The conclusion: are many dark corners of Perl, but you can see it as an opportunity to learn :-). The final solution was to wrap link into an anonymous subroutine (the explicit specification of parameters is needed because link is specified explicitly as "sub ($)", so the simpler @_ method doesn't work):


my $op = $condition ? \&move : sub { \&link($_[0], $_[1]) };

Hopefully this will help somebody out by pointing her in the right direction. And here is funny (and relevant to the situation :-p) quote to get you trough the day: "I distrust camels, and anyone else who can go a week without a drink." - Joe E. Lewis

Picture taken from Neil Carey's photostream with permission.

1 comment:

  1. Perl is the best scripting language for Text processing and handle regex. I have posted few articles related to those at my blog

    http://icfun.blogspot.com/search/label/perl

    Also Perl's Cpan has lots of support that I don't even need to think extra while developing project. I didn't find such help on other programming language except Java and .NET

    ReplyDelete