Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

An alternate way of implementing import with options

by rrwo (Friar)
on Feb 13, 2001 at 20:57 UTC ( [id://58153]=note: print w/replies, xml ) Need Help??


in reply to Re (tilly) 1: Passing parameters to a module's import function
in thread Passing parameters to a module's import function

An aside. Here's another way of coding it:

sub import { my $self = shift; my @exports = grep { "HASH" ne ref($_) } @_; my @options = grep { "HASH" eq ref($_) } @_; foreach (@options) { # handle options here } @_ = ($self, @exports); goto &Exporter::import; }

Question: will grep interfere with @_ (making the above a bit dangerous)?

Replies are listed 'Best First'.
Re: An alternate way of implementing import with options
by japhy (Canon) on Feb 13, 2001 at 21:32 UTC
    grep() won't do anything bad to @_, but I am personally against doing two operations in a row like you did that are complements.

    That being said, I'd rewrite the @_-filtering line as:
    my %args; push @{ $args{ref($_) eq 'HASH' ? 'opt' : 'ext'} }, $_ for @_;
    Or, I might even do a moving-splice() trick:
    sub import { my $self = shift; my ($i,$j,@options); for (@_) { if (++$j, ref($_) eq 'HASH') { push @options, splice(@_, $j + --$i, 1); $_ = $_[$j+$i], redo if $j + $i < @_; } } # handle @options # @_ now only holds elements which aren't hash refs $self->SUPER::import(@_); }
    </code>

    japhy -- Perl and Regex Hacker
      That fails. The point of the goto in the original is that Exporter checks caller to figure out what package to export symbols to. You have to use export_to_level() instead, and my experience suggests that that function is more likely to cause warning messages to come from the wrong place than I like. (Also with 5.6+ it will force you to load Exporter::Heavy which is slower. If that matters to you.)

      Aside from that, I don't like using explicit indexes if I can avoid it...

        Oh, d'oh, right. I knew there was some reason I knew goto was being used. So yeah, modify my code as needed. Silly jeffy.

        japhy -- Perl and Regex Hacker
Re: An alternate way of implementing import with options
by merlyn (Sage) on Feb 13, 2001 at 21:28 UTC
      That is morally the same as my original version. In fact before I posted I had thought about having 2 arrays, and then I thought that instead of tracking options, it probably made more sense to process in place. :-)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-19 05:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found