[Kc] subroutine parameter list

Kit Peters popefelix at gmail.com
Wed Apr 9 12:39:34 PDT 2008


Is there some compelling reason you can't just pass your parameters as
a hashref?

param_test({tom => "somestring", george => "anotherstring", ref => \@array});

sub param_test {
  my $args = shift;
  croak "Usage: param_test($hashref)" unless ref $args eq 'HASH';
  ....
}

On Wed, Apr 9, 2008 at 2:29 PM, Andrew Hanenkamp <sterling at hanenkamp.com> wrote:
> On Wed, Apr 9, 2008 at 12:14 PM, James Carman <developer at peelle.org> wrote:
>
> > Hey all,
> >
> > Is it possible to do something like:
> >
> >
> > &param_test("somestring", "another_string" $arrayref);
> >
> > sub param_test($tom; $george; @$array) {
> >     print $tom;
> >     ....;
> > }
> >
> >
> > #################
> > I am wanting to Specifiy how many arguments to take. Also I want to
> specify the name of the arguments. And also if possible the type of the
> arguments.
>
> Perl's concept of a subroutine prototype is unusual and there are some
> purists who will tell you to never use them. I think they are helpful when
> used carefully. In this case, this is about the best you can do:
>
> sub param_test($$\@) {
>     my ($tom, $george, $array_param) = @_;
>     ...
> }
>
> You would then call the subroutine (make sure you *don't* use &param_test()
> or Perl will ignore the prototype):
>
>  param_test("somestring", "otherstring", @array);
>
> The other alternative would be to declare param_test() like this:
>
> sub param_test($$@) {
>     my ($tom, $george, @array_param) = @_;
>     ...
>  }
>
> This could be called exactly the same way as before. The significant
> difference between the two is that in the first one, the $array_param
> variable is actually a references to the \@array passed, which means you can
> modify it in place. In the second case, you don't have a direct reference to
> the @array value to modify.
>
> The good thing is that if you call param_test() this way, it will warn you
> during compile that something isn't right when you try to use it without
> three parameters, specifically two scalars followed by an array.
>
> That's about it for compile time checking. For more details, you can see the
> "Prototypes" section of perlsub
> (http://search.cpan.org/search?query=perlsub&mode=all). If you want robust
> runtime checking, I second Andy's recommendation of Param::Validate.
>
> Cheers,
> Andrew
>
> _______________________________________________
>  kc mailing list
>  kc at pm.org
>  http://mail.pm.org/mailman/listinfo/kc
>



-- 
GPG public key fingerpint: 1A12 04B6 0C80 306A B292 14FD 2C7A 1037 F666 46A7


More information about the kc mailing list