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

'no strict "refs"' considered harmful?

Thread Next
From:
Jeff 'japhy' Pinyan
Date:
July 23, 2005 23:44
Subject:
'no strict "refs"' considered harmful?
Message ID:
Pine.LNX.4.61.0507240230560.23911@perlmonk.org
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;
   $obj->foobar(10);

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

   ClassName->foobar(10);

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
http://japhy.perlmonk.org/  %  have long ago been overpaid?
http://www.perlmonks.org/   %    -- Meister Eckhart

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About