Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Reading file and matching lines

by choroba (Canon)
on Feb 11, 2014 at 12:12 UTC ( #1074405=note: print w/ replies, xml ) Need Help??

in reply to Reading file and matching lines

In Perl, you can read a file line by line without the need to load the whole file first. Use the diamond operator in a while loop (untested code):

open my $IN, '<', 'quoteout.dat' or die "$!"; my $searching_for_G; while (<$IN>) { $searching_for_G = 1 if 0 == index $_, 'E'; die "Error: h at line $." if $searching_for_G and 0 == index $_, ' +h'; if ($searching_for_G and 0 == index $_, 'G') { print "Found G at line $.\n"; undef $searching_for_G; } }

Note that unlike in C, a string is not an array of characters in Perl (that's why I used index). Also, you did not specify what to do if G is found - should the program end or search for another E? I assumed the latter.

$. contains the input line number. See perlvar for details.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Comment on Re: Reading file and matching lines
Download Code
Replies are listed 'Best First'.
Re^2: Reading file and matching lines
by robby_dobby (Pilgrim) on Feb 11, 2014 at 12:56 UTC
    Wouldn't it be better if you had just used $searching_for_G and /^h/? (I haven't tested this). It may well just be me, but 0 == index ... sticks out oddly to my eyes.
Re^2: Reading file and matching lines
by Jalcock501 (Sexton) on Feb 11, 2014 at 13:26 UTC
    Apologies, Yes there are several instances of this in a single file, so I need to do this through out the file and only report any errors if there are any. If none the script should exit normally.
      "...only report any errors if there are any"

      If so, why not something simple like this:

      while (<IN>) { print qq($1\n) if /^(E)/; print qq($1\n) if /^(G)/; die $1 if /^(h)/; }

      Or do i still misunderstand the specs?

      Best regards, Karl

      «The Crux of the Biscuit is the Apostrophe»

      use strict; use warnings; my $infile = shift; my $found_E = 0; my $sets = 0; open my $ifh, '<', $infile; while(<$ifh>) { if (/^E/) { $found_E = 1; next; } if ($found_E) { if (/^G/) { $sets += 1; $found_E = 0; next; } if (/^h/) { print "Error! Found h before G\n"; exit; } } } close($ifh); printf "Found %d sets from E to G uninterrupted by h\n",$sets;

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2015-10-10 20:56 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (258 votes), past polls