Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Subroutine performing operation on variable submitted to it...

by tunafish (Beadle)
on Nov 24, 2011 at 07:17 UTC ( #939808=perlquestion: print w/replies, xml ) Need Help??
tunafish has asked for the wisdom of the Perl Monks concerning the following question:

Wasn't sure what to put in the title of the queston. I'm a little confused by the following behavior. I'm trying to strip the HTML tags from a variable and save that value to another variable. I have the following code:

$item->{'notag_title'}=&strip_tags($item->{'title'}); sub strip_tags { $_[0]=~s/<[^>]+>//gs; return $_[0]; }

As expected $item->{'notag_title'} becomes a tag-less version of $item->{'title'}. But $item->{'title'} loses its tags too! I don't understand it at all. Is $_[0] a reference to the original variable, not a variable local to the subroutine?

Replies are listed 'Best First'.
Re: Subroutine performing operation on variable submitted to it...
by davido (Archbishop) on Nov 24, 2011 at 07:41 UTC

    The answer is in perlsub.

    $_[0] becomes an alias to the sub's parameter. In this case, that param is $item->{'title'}, so the change ripples back as you've experienced.

    Do it this way:

    sub strip_tags{ my $string = shift; # Or my $string = $_[0]; $string =~ s/<[^>]+>//gs; return $string; }

    With that method you're making a copy of the string and working on it.


    Dave

Re: Subroutine performing operation on variable submitted to it...
by Eliya (Vicar) on Nov 24, 2011 at 07:38 UTC

    The elements of @_ are aliases to the arguments passed to the routine. "Alias" means you can access the same data under a different variable name. If you modify $_[0], you modify the original argument/value. It's not a reference in the sense of how the word is used in Perl context, because in this case you'd have to dereference it.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://939808]
Approved by Old_Gray_Bear
help
Chatterbox?
and the grasshoppers chirp...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2017-11-21 05:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (295 votes). Check out past polls.

    Notices?