in reply to printing alternate lines from a file

G'day perl_req,

Welcome to the monastery.

It would appear you're not really across how to open files in Perl. Take a look at open. Note how your code looks nothing like the examples given there. Compare with NetWallah's code (above) which does follow the documented format. (You're also closing the wrong filehandle - see close.)

Perl will tell you about various problems with your code if you ask it to. Add use strict; and use warnings; near the top of your code. If you find the messages it produces are a little hard to understand, also add use diagnostics; for longer, more descriptive explanations. (See: strict, warnings and diagnostics.)

Thanks for providing sample input. Unfortunately, you've put each line in its own HTML paragraph (<p>...</p>) which converts all strings of whitespace (spaces, tabs, newlines) to a single space. That's a lot of extra work for you but of no benefit to us: we can't see where the extra whitespace you've described occurs ("... output which is distorted ..."). For future reference, put the whole block of input (output, etc.) within <code>...</code> tags as you did with your code listing: less work for you, more useful for us.

Here's a solution which produces your desired output. I've added arbitrary tabs to the input to simulate the problem which I can't see (as just described).

#!/usr/bin/env perl use strict; use warnings; my $lines_per_block = 4; my $wanted_id = 'id2'; while (my $joined_block = join_block_of_lines($lines_per_block)) { next unless $joined_block =~ /^$wanted_id/; print $joined_block, "\n"; } sub join_block_of_lines { my ($lines_per_block) = @_; my @block_lines; for (1 .. $lines_per_block) { my $line = <DATA>; return '' unless defined $line; $line =~ s/\s*\n$//; push @block_lines, $line; } my $joined_line = join ' ' => @block_lines; $joined_line =~ s/\s*\t\s*/ /g; $joined_line =~ s/^(\S+)\s+(:)\s+/$1$2/; return $joined_line; } __DATA__ id1 : /a text lies here/ add name: new add1 ph no: new phone1 country: new country1 id2 : /some other text lies here/ add name: new add2 ph no: new phone2 country: new country2

Output:

$ pm_join_block_of_lines.pl id2:/some other text lies here/ add name: new add2 ph no: new phone2 c +ountry: new country2

-- Ken

Replies are listed 'Best First'.
Re^2: printing alternate lines from a file
by perl_req (Initiate) on Sep 13, 2012 at 01:40 UTC
    Hi Ken, Thank you so much for your reply. I have been trying couple of things but I am stuck at one of them. I will post the question soon if I am not able to solve it myself first. Thanks