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.


___________
Eric Hodges

In reply to Re: Return Question in Subroutine by eric256
in thread Return Question in Subroutine by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.