in reply to Problem with function

If $type is a variable that really needs to be available to your entire program, then you should put the declaration at the top of the file. However, in this case, I'd suggest that you consider passing it as an argument to your function:

sub print_summary { my ($type) = @_; if($type=~/w/) { print "hello\n"; } } # ... later ... print_summary("world");

Actually, what I'd probably do is more along these lines...

sub summary { my ($type) = @_; if($type=~/w/) { return "Hello, "; } elsif ($type =~ /h/) { return "world!\n"; } } # ... later ... print summary("world"); print summary("hello");

Notice here that the function returns the string to be printed, rather than printing it. This makes the function more reusable in the event that you need to send the results somewhere other than standard output, e.g., write them to a file, send them over a socket, or capture them to a string for subsequent processing.


Sanity? Oh, yeah, I've got all kinds of sanity. In fact, I've developed whole new kinds of sanity. Why, I've got so much sanity it's driving me crazy.

Replies are listed 'Best First'.
Re^2: Problem with function
by ruzam (Curate) on May 05, 2006 at 15:45 UTC
    If you're going to pass $type into the function I'd do this:
    sub summary { my $type = shift || return '';
    To avoid warnings later when someone forgets and tries to
    print summary();
      I think in that case I'd prefer to *have* the warnings.