Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: process array with while loop

by ikegami (Patriarch)
on Nov 09, 2006 at 17:09 UTC ( [id://583158]=note: print w/replies, xml ) Need Help??


in reply to process array with while loop

my @array = qw(blue red orange brown); # No commas in qw() foreach (@array) { print("$_\n"); }

See perlsyn.

<...> is used when reading from a file handle. It can also be used for globbing (as you are using it), but that's very fragile.

Update: Just noticed the commas in qw(). Addressed this.

Replies are listed 'Best First'.
Re^2: process array with while loop
by jbert (Priest) on Nov 09, 2006 at 18:44 UTC
    To elaborate (because this foxed me, I thought <> must have different behaviour when passed an array), as far as I can tell, the reason this appears to work is a result of:
    1. glob("pattern") returns "pattern" if no files match the pattern (this includes patterns which no metacharacters, such as 'blue');
    2. In a scalar context <pattern> is magic - it keeps state and returns each successive value of glob("pattern"). For example, create files touch tt1 tt2 tt3 and then run:
      print scalar <tt?>, "\n" for 1..3; # prints tt1, tt2 and tt3
      Note that (like the flipflop operator) each seperate instance of <pattern> appears to keep its own internal state.
      print scalar <tt?>, "\n"; print scalar <tt?>, "\n"; print scalar <tt?>, "\n"; # prints tt1, tt1, tt1
      And to drive the point home, fun with closures:
      my $s = sub { return scalar <tt?>; }; print $s->(), "\n"; print $s->(), "\n"; print $s->(), "\n"; # prints tt1, tt2, tt3
    So...this will "work" provided none of the array elements is a string which both contains a glob metacharacter and matches a file as a glob. (If the array elt doesn't contain any such chars, it doesn't matter if it matches or not - you'll get back the pattern).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://583158]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-23 13:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found