Is it hot in here? <tugs at shirt collar>

I guess I was thinking of another function, although I'd feel a little less
sheepish if I knew which one.  "$_ = shift @_" should work for the example.
Good point about catching strings that evaluate to FALSE.  I'll keep that in
mind.

Quick question:  What advantage is there to using local on the $_ variable?

-----Original Message-----
From: Jeff 'japhy' Pinyan
To: Timothy Johnson
Cc: [EMAIL PROTECTED]; [EMAIL PROTECTED]
Sent: 2/3/02 11:13 PM
Subject: RE: why shift @_ ?

On Feb 3, Timothy Johnson said:

>sub makeArray{
>   while(shift @_){
>      print $_."\n";
>   }
>}
>
>That way if you called the sub like this...
>
>   &makeArray('hello','world','!');
>
>You should get this...
>
>   hello
>   world
>   !

You SHOULD, but you don't.

>as your output.  'shift' removes the first element in an array and
returns
>the value.  If no variable is specified, the value is stored in the $_
>variable.  I have lately been converting some of my code to use this
format
>instead of foreach() loops because it is shorter and easier to read.

No, it doesn't automatically store it in $_ for you.  And, since you'll
have to explicitly store it in $_ yourself, you'd better local()ize $_.

  sub foobar {
    local $_;
    while ($_ = shift) {
      # ...
    }
  }

But that will stop when @_ has a value that's false (0, undef, or '').
So
to fix that, you'd want to use something like:

  sub foobar {
    local $_;
    while (@_) {
      $_ = shift;
      # ...
    }
  }

But there's really no reason NOT to use a for loop, which does most of
the
work for you, and is efficient.

  sub foobar {
    for (@_) {
      # ...
    }
  }

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]
http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/
http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002
**
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of
course.


--------------------------------------------------------------------------------
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