Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Foreach Loops

by Roy Johnson (Monsignor)
on Mar 15, 2005 at 20:52 UTC ( [id://439759]=note: print w/replies, xml ) Need Help??


in reply to Foreach Loops

my @arr = qw(cat dog pig horse donkey); for my $line (@arr) { my $index = (1=~//..1=~/0/)-1; print "$index = $line\n"; }
;-)

Another Bad Perl Solution.®

Replies are listed 'Best First'.
Re^2: Foreach Loops
by hubb0r (Pilgrim) on Mar 15, 2005 at 22:22 UTC
    Can you explain what the
    my $index = (1=~//..1=~/0/)-1;
    does??
      I'm so glad you asked!

      I am using a flip-flop as a counter. Of the conditions I gave it, the left side is always true and the right is always false, so the expression is always true. It is a property of the operator that it returns a count of the number of consecutive times it has been true. So subtracting one from that gives you the index.

      Unless there are redos or nexts, which would throw it off. So I really should have written

      my $index = 0; for my $line (@arr) { next if $index % 4 == 0; print "$index = $line\n"; } continue { $index = (1=~//..1=~/0/); }
      Well, actually, I shouldn't have written it at all as a solution to this question. But I like putting little-used operators into the spotlight so that people might think of them when they actually are appropriate.

      Caution: Contents may have been coded under pressure.
        (DROPS JAW)

        Pardon me, Roy, if I thank you; that is absolutely brilliant. (Include Guinness ad here.) I've never seen that before, and I wouldn't have thought of it in a month of Sundays. I have no idea where I would use that in place of normal indexing, but I might have to go out of my way to use this just to keep my coworkers from thinking that Perl is simple. Nothing like some obscurata for enhancing job security.

        --
        tbone1, YAPS (Yet Another Perl Schlub)
        And remember, if he succeeds, so what.
        - Chick McGee

        Jeezus! "little-used" would be the exaggeration of the day here!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-20 02:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found