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

I've done named arguments to a subroutine in perl before, but never with oop

can someone give me a pointer? do i just shift self, then coerce @_ into a hash? or is there a more elegant method?

i tend to prefer the the " my ( $self ) = @_ ; " assignment than the " my $self = shift; " or "my $self = @_[0];", so i'd like to see what all my options are.

Replies are listed 'Best First'.
Re: oop + named arguments
by jeffa (Bishop) on Apr 05, 2006 at 19:20 UTC

    I have used this with much success in the past:

    sub foo { my $self = shift; my %args = @_; do_something() if $args{jam_on_it}; }

    Have you considered, perhaps, using Params::Validate?

    my %args = validate(@_, { search_text => { type => SCALAR }, my_customer_id => { type => SCALAR }, });

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: oop + named arguments
by japhy (Canon) on Apr 05, 2006 at 19:22 UTC
      japhy,
      When I am doing this without using an existing wheel, it usually looks something like:
      sub thing { my $self = shift @_; croak "Incorrect number of arguments" if @_ % 2; my %arg = @_; for (@known_args) { # handle $arg{$_}; delete $arg{$_}; } if (keys %arg) { my $bad = join ' ', keys %arg; croak "The following args are invalid: $bad"; } # ... remainder of thing }

      Cheers - L~R