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

Let's say you have this:
my $example = Test::Blah->new(); $example->some_method( name => 'hello', age => '18', address => ['FL', 'Orlando', '2314', 'Bird St'] );
How do I make some_method() read in those named parameters?

Replies are listed 'Best First'.
Re: How to make an object method read named parameters?
by saberworks (Curate) on Oct 13, 2005 at 22:43 UTC
    use Data::Dumper; sub some_method { my $self = shift; my %params = @_; warn Dumper(\%params); }
      TIMTOWDI:
      sub some_method { my ($self, %params) = @_; # Do whatever }

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.
Re: How to make an object method read named parameters?
by snowhare (Friar) on Oct 14, 2005 at 03:18 UTC

    There are about a half dozen modules on CPAN including Params::Check, Params::Smart, Params::Named, Sub::Parameters, and Class::ParmList (I've omitted some modules that perform validation but no actual parsing of the passed parameters).

    Class::ParmList

    Mature, lightweight, and robustly portable all the way back to Perl 5.00x (Obligatory Disclosure: I wrote it). It also handles optional parameters, required parameters, legal parameters, parameter defaults, anon hash vs list parameters, and 'case flattening' of passed parameter names.

    Sub::Parameters

    Appears elegant, but has several module dependencies and is fragile. I could not get it to succcessfully install on any version of Perl I have on my desk machine (5.005_04, 5.6.2, 5.8.0 or 5.8.6).

    Params::Named

    Only works for Perl 5.8.x or later but is pretty clean. It can't handle 'case flattening', however.

    Params::Smart

    Requires at least Perl 5.6.x. Handles required and optional parameters and has advanced processing options available.

    Params::Check

    Portable (installs on Perl 5.00x and later), very powerful (supports optional, legal, required, validation, callbacks, and defaulted parameters and handles case flattening). Its downside is that there really isn't a 'simple' mode.

    Hash Assignment

    And there is always the classic, no bells and whistles, but fast and portable hash assignment:

    #!/usr/bin/perl use strict; my_sub( handle => 'Test', 'thing' => 'something'); sub my_sub { my %args = @_; my ($handle, $thing) = @args{'handle','thing'}; print "HANDLE: $handle\nTHING: $thing\n"; }
Re: How to make an object method read named parameters?
by shemp (Deacon) on Oct 13, 2005 at 23:15 UTC
    How about using Params::Check, or some other module that already does the real work for you?

    I use the most powerful debugger available: print!