Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: AUTOLOAD for variables?

by Chmrr (Vicar)
on Jul 08, 2004 at 04:48 UTC ( #372672=note: print w/ replies, xml ) Need Help??


in reply to AUTOLOAD for variables?

It's possible to do, if you hook into the warning that gets tossed when a variable is only used once. For example:

#!/usr/bin/perl -w use warnings; BEGIN { use Lingua::EN::Words2Nums; $SIG{__WARN__} = sub { if ($_[0] =~ /Name "(.*)" used only once/) { my $var = $1; my ($num) = $var =~ /::(\S+)/; $num =~ tr/_/ /; $$var = words2nums($num); } else { warn @_; } }; } print $five + $seventeen, "\n";

However, this is firmly in the "sick trick" arena, rather than "maintable code." Heed the other monks' advice to look for better ways to go about this.

Update: Oh, yeah -- this obviously only works if you only refer to the variable once in your code. This may be more trouble than it is worth, obviously. It also won't catch things like $foo = "five"; print $$foo;


Comment on Re: AUTOLOAD for variables?
Select or Download Code
Re^2: AUTOLOAD for variables?
by dpuu (Chaplain) on Jul 08, 2004 at 06:00 UTC
    I like the trick but, unfortunately, the evil of my users far surpasses it. Its not uncommon to see code such as:
    my $value= ${ uc join "_", @$reg_spec{ qw( device reg field ) } };
    You really don't want to see some of the more nasty code. Honest. Especially not the 70000 line regex (its one saving grace is the /x modifier). And perhaps not the script that parses another script's --verbose output. Or perhaps ...

    --Dave
    Opinions my own; statements of fact may be in error.
      Create an API. Create a set of expected standards. Give your users 3-6 months to comply with those standards, then issue the smack-down. Period. You can't do everything for everyone.

      ------
      We are the carpenters and bricklayers of the Information Age.

      Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      I shouldn't have to say this, but any code, unless otherwise stated, is untested

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (12)
As of 2014-11-28 17:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (199 votes), past polls