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

Re: Different behaviors between "while" and "map"

by friedo (Prior)
on Dec 06, 2008 at 00:08 UTC ( #728437=note: print w/replies, xml ) Need Help??

in reply to Different behaviors between "while" and "map"

The reason this happens is because the while loop is designed to operate on <> like an iterator. Thus, it reads one line at a time until it can't read anymore.

By contrast, using <> as the list for your map block reads the entire file in all at once, incrementing $. along the way. The entire file then gets passed to your map block as one big list, and by this time, $. has already been incremented to the number of the last line, so the same $. gets printed each time through the map block.

Replies are listed 'Best First'.
Re^2: Different behaviors between "while" and "map"
by Joost (Canon) on Dec 06, 2008 at 00:43 UTC
    Just to expand a little on this: map, grep, foreach and most while constructs all work on perl's concept of lists.

    while (<SOME_FILE_HANDLE>)
    is special. it does not act like any other iteration construct, not even like any other while() construct. It explicitly iterates over each record ("line") one by one instead of converting the whole file to a list first.

      It helps to know that the loop is expanded to:

      while ($_ = <SOME_FILE_HANDLE>){ ... }

      This shows that <...> is nothing more than a loop condition: the loop body is executed immediately after each evaluation of the <...> operator. This is how a while loop works.

        Not for the last 12 years or so. It's expanded to
        while (defined ($_ = <SOME_FILE_HANDLE>)) { ... }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://728437]
[shmem]: in the french alpes, at the end of a gravel road, we had a beer at a hut - and heard an enduro coming up.
[shmem]: not by the road, but from there below where you wouldn't want to walk.
[shmem]: the biker stopped the machine at the table and took off his helmet.
[shmem]: long white hair, long beard the same, then he proceeded to get off the bike
[shmem]: saying "biking itself isn't that much, but getting up and down - hell!"
[shmem]: up and down: on and off the bike, of course

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2017-06-25 20:11 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (570 votes). Check out past polls.