Okay, that makes sense after playing around with it a little.  One more
question.  Does that offer an advantage over doing this?

use strict;
our @list = qw(a b c d);
foreach (@list) {
  &check_b;
  print $_, "\n";
}


sub check_b {
  foreach (@list) {
    my $string = $_;   #instead of local $_
    $string =~ s/b/bb/;
    # SAVE TO FILE
  }
}

-----Original Message-----
From: Dave Benware [mailto:[EMAIL PROTECTED]]
Sent: Monday, February 04, 2002 7:00 PM
To: Beginners perl
Subject: Why localize $_, was-> Re: why shift @_ ?


Timothy Johnson wrote:
> 
> Ok, I figured that much, but I guess my question is this:  Is there a
> pressing need to scope a predefined variable like $_?  How could this
> adversely affect a program?  (I'm not trying to be a smart aleck, I really
> want to know)
> 


Hi,
Sorry for such a short answer in my first post, but actually,
scoping is brand new to me, so I was shy of going into a lot
of details on the matter.

However, since the whole idea behind using local or my with variables
is to prevent a variable name from writing over the same variable
name elsewhere in the script, it makes even *more* sense to me to
use local with Perl's special variables; in that they are used frequently 
throughout one's script, (with different values/purposes).

If $_ were a constant value like pi throughout a script, that would be 
different.  Then there would be no purpose in scoping it.


Since I couldn't understand Jeff's code, (no offense, I'm new), I
wrote a script to demonstrate how the value of $_ could get changed
unexpectedly.  (It took me an hour, but I learned from it, heh).


# THE MAIN PROGRAM PRINTS AN ARRAY.  HOWEVER IT ALSO CALLS
# A SUBROUTINE THAT CHECKS EACH ELEMENT FOR "b".  IF "b" IS
# FOUND, IT SAVES IT IN A FILE.  THE SUBROUTINE SHOULD BE
# HARMLESS, RIGHT?

use strict;
our @list = qw(a b c d);
foreach (@list) {
  &check_b;
  print $_, "\n";
}


sub check_b {
  foreach (@list) {
    #local $_;
    $_ =~ s/b/bb/;
    # SAVE TO FILE
  }
}


As is, @list is printed incorrectly, but if you uncomment #local $_;,
it'll print as expected.

Bompa

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]


--------------------------------------------------------------------------------
This email may contain confidential and privileged 
material for the sole use of the intended recipient. 
If you are not the intended recipient, please contact 
the sender and delete all copies.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to