in reply to Subroutine that modifies actual variable

I believe Perl uses what's called a 'pass by reference' method to give variables to a function (only important to remember the name in other languages, e.g., C/C++, where you have a choice of by value or by reference). Anyway, what this means is that you can actually modify the variable inside the function without doing anything special. E.g.:
sub delete_first_char { $_[0] =~ s/^.// }

That code would delete the first character of a string (admittingly not the best way to do it). However, most subroutines you see do this:
sub whatever { ($var1,$var2,$etc) = @_; ... }

They do this so that they don't mistakingly alter/change the variable that was passed to them. Usually this is a good coding practice, however, quite certainly situations do arise where you wish to modify the variable that you pass in, in which case you just refer to it directly; i.e., $_[--elm # here--].

Replies are listed 'Best First'.
Re: Re: Subroutine that modifies actual variable
by darkomen (Acolyte) on Jul 11, 2001 at 21:30 UTC
    I feel rather silly, since i've been coding perl for around a year and have never tried to modify $_[0] directly, i've always assigned it to another var. Thank you.