Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How to Print Every Other Line

by davido (Cardinal)
on Jun 30, 2004 at 17:33 UTC ( [id://370823]=note: print w/replies, xml ) Need Help??


in reply to How to Print Every Other Line

Some explanation of the proposed solutions is in order.

The special variable $. contains a count of the number of lines read from the most recently read filehandle. This number starts with 1. So reading a file line by line, $. will be set to 1, 2, 3, and so on for each respective line read. Read perlvar for details.

This is a convenience, though in this simple case, it's almost as easy to set your own iterator up ahead of time and autoincrement it prior to processing each line read.

The next step is determining even and oddness of a number. One of the easiest ways is to find out the remainder when you divide a number by two. The "remainder" is the modulus of X / 2. And the modulus function is named %. So $x % 2 will be zero for even numbers, and some value for odd numbers. See perlop for more info.

So if you put the two pieces together, and check $. % 2 for value, if it contains any value other than zero, you're looking at an odd line number, and should print that line.

Another solution is to just treat the filehandle as a queue. Instead of shifting one item per loop iteration, shift two, and discard the second, and print the first each time.


Dave

Replies are listed 'Best First'.
Re^2: How to Print Every Other Line
by melora (Scribe) on Jun 30, 2004 at 20:33 UTC
    "The "remainder" is the modulus of X / 2. And the modulus function is named %. So $x % 2 will be zero for even numbers, and some value for odd numbers."

    Some value should be one, right? (well, anyway, non-zero is true, so I'm nitpicking.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (10)
As of 2024-04-19 09:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found