Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: aliasing subs

by edan (Curate)
on May 06, 2003 at 11:37 UTC ( [id://255843]=note: print w/replies, xml ) Need Help??


in reply to aliasing subs

I agree with the valid points that were already rasied:

  1. use File::Spec (or, I might add, File::Basename) to do this - don't reinvent the wheel.
  2. just re-organize the code, put the shared code (i.e. the reg-exp, in this case) in a subroutine, and call that from two different routines

However, my curiosity was piqued about how to go about this, if the need did come up somehow, even though I think solution #2 would be the simplest/best answer most (all?) of the time...

So I came up with this snippet using closures, as you mentioned

for my $wheel (qw/basename dirname/) { no strict 'refs'; *$wheel = sub { my ($dir) = shift; my ($path, $name) = ($dir =~ m{(.*)/([^/]*)$}); if ($wheel eq 'basename') { return $name; } else { return $path; } }; } my $path = dirname('/tmp/foo/bar'); my $name = basename('/tmp/foo/bar'); print "$path/$name\n";

Works for me...

Update: Expunged the OPs leaning toothpicks, since I am attributing the snippet to myself ;-)

Update: Or this:

for my $funcname (qw/basename dirname/) { no strict 'refs'; *$funcname = sub { my ($dir) = shift; my ($path, $name) = ($dir =~ m{(.*)/([^/]*)$}); if ($funcname eq 'basename') { return $name; } else { return $path; } }; } my $path = dirname('/tmp/foo/bar'); my $name = basename('/tmp/foo/bar'); print "$path/$name\n";
--
3dan

Replies are listed 'Best First'.
Re: Re: aliasing subs
by december (Pilgrim) on May 06, 2003 at 12:16 UTC

    Nice. That's what I tried already too, but it looked very complex to me, considering what I was trying to do. Seems to me dispatching functionality with aliased sub names (like some unix commands do) is one major benefit of aliases, but it doesn't appear to be possible... which is a pity.

      I don't know but ... if I make an alias I expect the alias to behave exactly as the original. And not to notice I called it differently and starting to complain that it aint Larry, but Mr. Wall.

      If it's supposed to behave differently it should be a different subroutine.

      Jenda
      Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
         -- Rick Osborne

      Edit by castaway: Closed small tag in signature

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://255843]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (1)
As of 2024-04-24 13:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found