in reply to Using import to generate subroutines

how do I write my own "import" ?

This is one of the few cases where I think symbolic refs make things much easier. Here's how I'd probably do it:

package MyProcedures; use strict; use warnings; sub import { my $class = shift; my $caller = (caller)[0]; no strict 'refs'; for my $f (@_) { *{"$caller\::$f"} = sub { print "$f\n" }; } } 1;

And then it can be used like so:

$ perl -e 'use MyProcedures qw(one two three); one(); two(); three();' one two three

Replies are listed 'Best First'.
Re^2: Using import to generate subroutines
by Thilosophy (Curate) on Nov 24, 2004 at 02:42 UTC
    no strict 'refs'; for my $f (@_) { *{"$caller\::$f"} = sub { print "$f\n" }; }
    Thanks, that works.
      Although it makes no difference here, in general it's better to write that as
      for my $f (@_) { no strict 'refs'; *{"$caller\::$f"} = sub { print "$f\n" }; }
      This limits the scope of the no strict 'refs'. Otherwise, if you add any more code after the foreach, it will not be checked with strict.

        I put no strict 'refs' outside the loop because I didn't like the idea of running it repeatedly. I doubt it makes much of a difference in terms of performance, but it just didn't feel right in terms of semantics. I only wanted to turn it off once, not N times.

        That said, your concern is valid. Maybe we can reach a compromise:

        sub import { my $class = shift; my $caller = (caller)[0]; { # limit the scope of unstrict refs no strict 'refs'; for my $f (@_) { *{"$caller\::$f"} = sub { print "$f\n" }; } } }

        Update: thanks to fergal for the clarification. I disavow this post. :-)