Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Aliasing a builtin?

by xiper (Friar)
on Mar 11, 2003 at 04:21 UTC ( [id://241938]=perlquestion: print w/replies, xml ) Need Help??

xiper has asked for the wisdom of the Perl Monks concerning the following question:

Simple question: How does one go about creating an alias for a builtin function that acts identically? Eg.
# <magic code to alias "len" to "length"> foreach ( @array ) { print len; }

Replies are listed 'Best First'.
Re: Aliasing a builtin?
by chromatic (Archbishop) on Mar 11, 2003 at 04:52 UTC
    sub len { length; } my @array = qw( fu bar baaaaz ); foreach ( @array ) { print len; }

    If that's all you want, there you go. Beware of a couple of things though. First, you'll need to make sure that Perl knows what len means -- either declare the sub before, as I have done, or use a forward declaration. Second, some built-ins have special prototypes. You can use prototype to discover them. There are a couple of gotchas I always have to look up documented there.

      Also, this will break in Perl 6, where $_ is lexically scoped rather than global. (There are other ways to get the same effect in Perl 6, but I don't know if the translator will recognize what you have there as something that needs translating.)
Re: Aliasing a builtin?
by graff (Chancellor) on Mar 11, 2003 at 04:58 UTC
    Is this sort of a hang-over from using an interactive shell, like you're looking for a way to save a few keystrokes when typing in a perl program, so you'd like some mechanism in perl similar to the common shell alias idiom?

    In general, this is not worhwhile, unless obfuscation is one of your goals. Most perl programmers rely on having the builtins look the way they are described in perlfunc, and having them look different may cost more time for others to decipher code than what you saved by using fewer keystrokes.

    The best savings are from factoring the coding task so that as little as possible needs to be typed (or pasted) multiple times, rather than simply shortening some strings that you think you need to type often.

    BTW, a number of decent code editors provide something like aliases (emacs calls it "abbrev-mode"), where you can define a sequence of a few characters to act like a macro to insert a longer string.

            In general, this is not worhwhile, unless obfuscation is one of your goals.

      Bingo.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://241938]
Approved by graff
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-03-29 09:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found