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

(was: Regarding files)

Thread Previous
May 21, 2007 12:16
(was: Regarding files)
Message ID:
"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?

  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 = '';
      else { die "ugly phase($phase)"}
  $phase == 2 and print $s;


But a real parser would also catch variants such as

typedef union {
    TYPE_T type;
   MODE_T mode;

See also:

Affijn, Ruud

"Gewoon is een tijger."

Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About