in reply to File parsing query

Something like this?
my $widgets_found; while (<>) { print; if (/^DATABASE:/) { print "Widgets found: $widgets_found\n"; $widgets_found = 0; } if ( $something ) { $widgets_found++; } }

Replies are listed 'Best First'.
Re: File parsing query
by kryptonite (Initiate) on Feb 16, 2005 at 20:35 UTC
    Thanks for the quick reply. I have a similar start to that, but my problem lies in doing this: once I find the "DATABASE:" (the current one) I have to track widgets until the next occurrence of "DATABASE:" and then post the quantity in the line below the current "DATABASE:" line. That's where I'm stuck. I need to pause the parse and go back, then go forward again. I hope this makes sense...
Re^2: File parsing query
by eieio (Pilgrim) on Feb 16, 2005 at 20:43 UTC
    I think the OP wanted to output the count of widgets at the top of the database section which was counted. That is, something more like this:
    my $widgetsFound=0; my $databaseName; my $databaseSection; while( <> ) { if( /^DATABASE:/ ) { if( $databaseName ) { print $databaseName; print "Widgets found: $widgetsFound\n"; print $databaseSection; } $databaseName = $_; $databaseSection = ""; $widgetsFound = 0; } else { $databaseSection .= $_; } if( $something ) { $widgetsFound++; } } # print the last database section that was parsed if( $databaseName ) { print $databaseName; print "Widgets found: $widgetsFound\n"; print $databaseSection; }
    Updated: to correct errors noticed by Animator (who answered the original question first as well :) ).

      Some important notes:

      • $widgetsFound is not intialised at the start, which can lead to an undefined value that is printed (if there are no widget in the first database-section)
      • The printing of the last database section is always done, even if the file would be empty, which will lead to three undefined values being printed.

      An unimportant note: I posted similar code as a reply to the OP's node before you did :)