Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Determine first element in foreach

by neilwatson (Priest)
on Aug 04, 2014 at 18:01 UTC ( [id://1096172]=note: print w/replies, xml ) Need Help??


in reply to Determine first element in foreach

You can use a for loop instead of foreach

for ($i = 0; $i < $#mylist ; $i++) { say "first element" if ( $i == 0 ); }

Neil Watson
watson-wilson.ca

Replies are listed 'Best First'.
Re^2: Determine first element in foreach
by tobyink (Canon) on Aug 04, 2014 at 20:12 UTC

    Even when you want to loop over the indexes, you can still use a foreach-style loop:

    foreach my $i (0 .. $#mylist) { say "first element" if ( $i == 0 ); }

    foreach-style loops are generally a better idea that C-style for loops. They're clearer; more declarative. It's harder to introduce an off-by-one error, and easier to spot a mistake.

      It's harder to introduce an off-by-one error, and easier to spot a mistake.

      Indeed. Consider
          for ($i = 0; $i < $#mylist ; $i++) { ... }
      in reply above:  $i < $#mylist vice  $i <= $#mylist — or did you have that in mind?

        I hadn't even noticed that! (Which is precisely my point.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (8)
As of 2024-04-18 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found