Question

I am doing some text parsing using flip-flop operator and my data looks like below:

COMMAND START

CELL
123

COUNTER1    COUNTER2    COUNTER3
23          25          45

COUNTER1    COUNTER2    COUNTER3
22          34          52

CELL
234

COUNTER1    COUNTER2    COUNTER3
12          35          35

END

Now i need to iterate through this data and for each CELL, find the Sum of COUNTER2. Under each cell as we can see there might be 1 or more COUNTER rows. I tried using flip-flop operator like below, but its not working.

my ($CELL_ID_COL1, $TEMP_COUNT);
my @line_contents;

while (<>) {
    chomp;
    if(/^COMMAND.*START$/ .. /^END$/) {

        if (my $e1 = /^CELL$/ ... (/^CELL$/ || /^END$/)) {
            if ($e1 == 2) {
                @line_contents = split(/\s+/, $_);  #Split the line read on whitespaces
                $CELL_ID_COL1 = $line_contents[0];
                print "$CELL_ID_COL1\n";
                $TEMP_COUNT = 0;
            }

            if (my $e2 = /^COUNTER1.*COUNTER3$/ ...(/^COUNTER1.*COUNTER3$/ || /^CELL$/ || /^END$/) ) {
                print "$_\n";
                if ($e2 ==2) { 
                    @line_contents = split(/\s+/, $_);  #Split the line read on whitespaces
                    $TEMP_COUNT += $line_contents[1];
                }
                if ($e2 =~ /E0$/) {
                    redo;
                }

            }
            if ($e1 =~ /E0$/) {
                print "FINAL COUNT is: $TEMP_COUNT\n";              
                redo;
            }

        }
    }
}

I think this got to do something with the global state of flip-flop operator discussed in this question, but could not understand much. Please help me.

Thanks a lot in advance.

Was it helpful?

Solution

I think it's easier without the flip flop. Sometimes you start off thinking a feature is the way to go, but then you run into problems. Instead of resisting the urge to stick with the feature until you force it into the round whole, consider a completely different way to do it"

use Data::Dumper;
use List::Util qw(sum);

my %cells;
my $cell_id;
my $started;

while( <DATA> ) {
    $started++ if  /COMMAND START/;
    next unless $started;
    next if /\A\s*\z/;
    last if /END/;

    if( /CELL/ ) {
        chomp( $cell_id = <DATA> );
        $index = 0;
        }

    if( /COUNTER/ ) {
        my @counters = ( <DATA> =~ /([0-9]+)/g );
        $cells{$cell_id}[$index++] = \@counters;
        }
    }

my %sums;
foreach my $cell_id ( keys %cells ) {
    $sums{$cell_id} =  sum map { $_->[1] } @{$cells{$cell_id}}
    }

print Dumper( \%cells, \%sums );

You can also modify this to accumulate the sums as you go.

However, if you still want to use the flip flop, you can read Respect the global state of the flip flop operator and Make exclusive flip-flop operators

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top