Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^5: Using a scalar as a constant?

by suaveant (Parson)
on Oct 15, 2008 at 14:22 UTC ( #717236=note: print w/replies, xml ) Need Help??


in reply to Re^4: Using a scalar as a constant?
in thread Using a scalar as a constant?

You can even do it in a strict safe manner :)
use constant test => 5; if(my $sub = __PACKAGE__->can('test')) { print $sub->(),"\n"; }

                - Ant
                - Some of my best work - (1 2 3)

Replies are listed 'Best First'.
Re^6: Using a scalar as a constant?
by JavaFan (Canon) on Oct 15, 2008 at 15:24 UTC
    That wouldn't work if the sub is AUTOLOADED, and the package doesn't redefine 'can' to reflect this. (I've seen many packages using AUTOLOAD that don't redefined 'can').

    Having said that, and given the fact the subname comes from some XML document whose creation may not be under our control, I would neither use eval, nor a symref, and not can either. I'd make a dispatch table allowing only values I approve of.

    my $style = ... retrieve from XML document ... my $value; given ($style) { when ("sub1") {$value = sub1} when ("sub2") {$value = sub2} ... default {die "Illegal style '$style'"} } Wx::TextCtrl->new( $self, -1, "", [5, 10], [-1, -1], $value);
      That wouldn't work if the sub is AUTOLOADED, and the package doesn't redefine 'can' to reflect this. (I've seen many packages using AUTOLOAD that don't redefined 'can').

      It also won't work if you've edited the Perl source code and removed support for AUTOLOAD, which also produces broken behavior. Using AUTOLOAD without predeclaring your subs or overriding can() is a bug.

      In the case of constants I don't think you often have to worry about autoloading, but it is a good point.

      And dispatch tables are always good.

                      - Ant
                      - Some of my best work - (1 2 3)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2022-10-06 09:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My preferred way to holiday/vacation is:











    Results (26 votes). Check out past polls.

    Notices?