I don't know if you are aware but that code is actualy modifying the string in place AND returning it. Since you are using $_[0] (which is an alias) and changes made to it are made to the string passed to it. Sometimes this is expected, and sometimes it isn't. Sense you are using it on param i don't think it matters, but it might lead to some unexpected results. Below is the code I would use assuming that the codes job is to process an incoming param and make ti usabel. To me that cleanup process should also invovled hiding the fact that it was undef.
use strict; use warnings; my $str = "<some> text with';*()/? nasty chars. scripted is ok, but no +t script"; sub cleanup { my $p = shift; return '' unless defined $p; $p =~ tr|<>;()"'?/*||d; $p =~ s/\bscript\b//g; return $p; } sub cleanup2 { $_[0] =~ tr|<>;()"'?/*||d; $_[0] =~ s/\bscript\b//g; return $_[0]; } print "\$str is: $str\n"; print "Cleaned up: " . cleanup($str) . "\n"; print "\$str is: $str\n"; print "Cleaned up: " . cleanup2($str) ."\n"; print "\$str is: $str\n";
This outputs:
$str is: <some> text with';*()/? nasty chars. scripted is ok, but not +script Cleaned up: some text with nasty chars. scripted is ok, but not $str is: <some> text with';*()/? nasty chars. scripted is ok, but not +script Cleaned up: some text with nasty chars. scripted is ok, but not $str is: some text with nasty chars. scripted is ok, but not
Notice how the last print of $str is already cleaned, even though we never said $str = cleanup($str); . While this could be the desired behaviour it could also be very confusing for anyone using your code.
In reply to Re: Return Question in Subroutine
by eric256
in thread Return Question in Subroutine
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |