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.


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

Reply via email to