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

I am off on a jobsite without my trusty Perl CD Bookshelf.

I need(want) to pass named parameters to a subroutine, ala CGI..

do_this_cool_function (-retire=>'early', -payscale=>-55.00, -pizza=>'cold', -beer=>none);

I'm using 'use strict' and '-w'. The compiler throws up on my shoes with
"Can't use string ("-spot") as a HASH ref while "strict refs" in use at t.pl line 13."

A) What do I need to do remove this error,
B) How do I access the named arguments in the subroutine?.

Thanks, -- John
  • Comment on Passing named parameters to subroutines

Replies are listed 'Best First'.
Re: Passing named parameters to subroutines
by btrott (Parson) on May 02, 2000 at 03:54 UTC
    A) Is that the actual code you're using? It doesn't generate any errors for me. And I'm using strict and -w, so that must not be your code. Although I do get an error for your use of the bareword "none"--you should quote that.

    B) I usually just do something like this--load the parameters into a hash:

    sub do_this_cool_function { my %params = @_; for my $k (keys %params) { print $k, " => ", $params{$k}, "\n"; } }
    From glancing at its code, CGI.pm does some really fancy stuff under the hood to rearrange the named parameters. I've never found that necessary for my purposes, but it may be worth checking out if you feel the need to go advanced. :)
      Thanks! I suspected that the subroutine should pickup the parameter as a hash.

      I, uhhh, apparently had a problem in the do_cool_stuff routine that was actually causing the problem. Tired user overlooking something obvious... sigh.

      -- John