Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re^3: Using a scalar as a constant?

by Corion (Patriarch)
on Oct 15, 2008 at 13:29 UTC ( [id://717219]=note: print w/replies, xml ) Need Help??

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

Ah. If you have

my $style = 'wxTE_MULTILINE';

and want to get at the value returned by the constant/function wxTE_MULTILINE, then you have to use eval:

print $style; $style = eval $style; die $@ if $@; print $style;

Replies are listed 'Best First'.
Re^4: Using a scalar as a constant?
by JavaFan (Canon) on Oct 15, 2008 at 14:10 UTC
    An eval is possible, but some people rather avoid eval. You can avoid eval by making use of a symbolic reference:
    my $style = 'wxTE_MULTILINE'; { no strict 'refs'; say &$style; # or: say $style->() }
      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)

        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);
Re^4: Using a scalar as a constant?
by Anonymous Monk on Oct 15, 2008 at 13:56 UTC
    That did the trick...Thanks!

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-23 10:23 GMT
Find Nodes?
    Voting Booth?

    No recent polls found