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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Problem with function
by ruzam (Curate) on May 05, 2006 at 15:45 UTC | |
by jonadab (Parson) on May 05, 2006 at 21:23 UTC |