logo       

Re: On using $_ in subroutines: msg#00367

perl-beginners

Subject: Re: On using $_ in subroutines

Bryan Harris wrote:

Is it not possible to use $_ in subroutines?

Yes it is, just not the way you seem to want to use it.


For example, my temptation was to do this:

**************************************
sub isDate {

$_ = shift;
if (m!\d{2}/\d{2}/\d{2}!) { return 1; }
else { return 0; }


}

Why is this in a subroutine at all? If you are using it like:

if ( isDate() ) { #use $_ by default

Then just do this instead:

if ( m!\d{2}/\d{2}/\d{2}! ) {

Or use a variable instead:

my $isDate = qr!\d{2}/\d{2}/\d{2}!;

...

if ( /$isDate/ ) {


**************************************

... but by modifying $_ I was clobbering $_ elsewhere in the larger program!

Yes because $_ is a special global variable. This effect is called "action at a distance" which is why it is better to use named lexically scoped variables instead of $_.


Oddly, perl won't let me do "my ($_) = shift;", so I'm stuck having to use
another variable.

Perl 5.10 *will* let you do "my $_".


Why can't we do that? Is using $_ in subroutines discouraged??

Yes, precisely for the problems that you discovered.



John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscribe@xxxxxxxx
For additional commands, e-mail: beginners-help@xxxxxxxx
http://learn.perl.org/


Google Custom Search

News | Mail Home | sitemap | FAQ | advertise