Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Strict and runtime sub names

by Scarborough (Hermit)
on Sep 10, 2004 at 10:08 UTC ( [id://390013]=perlquestion: print w/replies, xml ) Need Help??

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

I'm currently working using an eval to capture errors in subroutines and this is a very slimmed down version of what i'm doing

#use strict; use vars qw($AUTOLOAD); &mysub_('foo','bar'); sub mysub{ #do something... print "in mysub\n"; return; } sub AUTOLOAD{ my @args = @_; $AUTOLOAD =~ /.*::(.*)_/ my $sub_name = $1; #no strict 'refs'; eval{&$sub_name(@args)}; #use strict 'refs'; print @; #do something with $@ to check runtime errors }

With strict commented out it works exactly as I had hoped but with strict back in $@ contains the messaage
Cant use string ("mysub") as sub routine ref while strict refs in use

I've got round it with turning strict refs on and off (commented out at the moment) but I'm not sure if this is a good way of dealing with the problem.Any ideas

Replies are listed 'Best First'.
Re: Strict and runtime sub names
by ysth (Canon) on Sep 10, 2004 at 10:26 UTC
    Since you have the eval block there, it would seem more natural to do:
    eval { no strict "refs"; &$sub_name(@args) }
    No need to turn it back on afterward; the no strict is scoped only to that block.

    You can get away without no strict, doing something like:

    eval { @_ = @args; goto &$sub_name }
    but IMO that just obscures what you are doing.
Re: Strict and runtime sub names
by broquaint (Abbot) on Sep 10, 2004 at 11:43 UTC
    I'd simply check if the subroutine exists and if so create the subroutine otherwise croak
    use strict; use Carp 'croak'; sub AUTOLOAD { my($name) = $::AUTOLOAD =~ /::([^:'_]+)_$/; my $method = __PACKAGE__->can($name) || croak "Undefined subroutine &$::AUTOLOAD called"; no strict 'refs'; goto &{ *$name = $method }; } sub foo { print "got: @_\n" } foo_(qw/ some args/); __output__ got: some args
    HTH

    _________
    broquaint

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-25 17:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found