develooper Front page | perl.beginners | Postings from May 2007

(was: Regarding files)

Thread Previous
From:
Dr.Ruud
Date:
May 21, 2007 12:16
Subject:
(was: Regarding files)
Message ID:
20070521191626.4146.qmail@lists.develooper.com
"Dharshana Eswaran" schreef:

You really shouldn't quote text that is no longer relevant, such as
signatures and mailing list tails.

> Ruud:
>> Dharshana Eswaran:

>>> i am trying to grep for a string in the file and once i get the
>>> string, I need to read few lines which occurs before the string.
>>
>> The classic (state machine) approach is to start storing strings from
>> the start marker, so "typedef union" here, and discard the stored
>> lines when the search string doesn't pop-up.
>
> Can you please help me with a small piece of code for the same logic
> which you mentioned?

#!/usr/bin/perl
  use strict;
  use warnings;

  my $phase = 0;
  my $s;
  while (<>) {
      if    (0 == $phase) {
          /^\s*typedef union\s*(?:\{\s*)?$/
            and ++$phase and $s = $_;
      }
      elsif (1 == $phase) {
          $s .= $_;
          if (/^\s*}\s*(\w+)\s*;\s*$/) {
              'CHANNEL_INFO_T' eq $1
                and ++$phase and last;
              $s = '';
              $phase--;
          }
      }
      else { die "ugly phase($phase)"}
  }
  $phase == 2 and print $s;
__END__

(untested)


But a real parser would also catch variants such as

typedef union {
    TYPE_T type;
   MODE_T mode;
}
CHANNEL_INFO_T;

See also:
http://search.cpan.org/search?query=balanced&mode=module

-- 
Affijn, Ruud

"Gewoon is een tijger."


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About