develooper Front page | perl.perl5.porters | Postings from July 2005

'no strict "refs"' considered harmful?

Thread Next
Jeff 'japhy' Pinyan
July 23, 2005 23:44
'no strict "refs"' considered harmful?
Message ID:
That sounds sillier than my concern actually is.  I noticed today (I don't 
know why today, and not the days before when I've seen this common idiom) 
that a person creating dynamic functions did the following:

   use strict;

   # ...

   for (@function_names) {
     no strict 'refs';
     *$_ = sub {
       # ...

I've seen that in various perldocs, and it seems to be a common practice 
when it comes to defining dynamically named functions.  But there's a very 
specific flaw inherent here.

   use strict;

   my @method_names = qw( foobar quux xyzzy );

   for my $m (@method_names) {
     no strict 'refs';
     *{ "ClassName::$m" } = sub {
       my ($self, $val) = @_;
       $self->{$m} = $val;

This sets up a bunch of methods for some object of class ClassName.  The 
idea being you can now say

   my $obj = ClassName->new;

and set $obj->{foobar} to 10.  But what if you slip up and write


As Scooby-Doo would say, "RUH ROH!"  We turned off strict's grip on 
references, and now we've accidentally worked with a symbolic reference. 
And strict won't mind a bit!

Although it looks a bit clunkier, I would suggest changing the idiom to

   for (...) {
     my $code = sub { ... };
     no strict 'refs';
     *$_ = $code;

Jeff "japhy" Pinyan         %  How can we ever be the sold short or
RPI Acacia Brother #734     %  the cheated, we who for every service  %  have long ago been overpaid?   %    -- Meister Eckhart

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About