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


In reply to Re: How to Print Every Other Line by davido
in thread How to Print Every Other Line by Neuroactive

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.