Perl Loop Conceptualization -


i'm having trouble trying figure out how attack problem. have file looks :

1 1 1 1 1 1 2 1 1 1 3 4 4 4 1 1 1 4 4 4 2 2 2 2 3 3 3 2 b 2 2 2 1 1 1 1 b 

which, want count how many times first 3 numbers repeat consecutively. in load data set perl, , spit out:

3 2 

as string '1 1 1' found @ start of line 3 times in row, , string '2 2 2' found begin line 2 times in row. either string may appear later in file, complicates things. well, not know beginning string either, , varies.

honestly, i'm confused on how attack this. if can conceptualize this/ give me pseudo-code help, great.

edit: per borodins answer, works asked. however, if wanted print count plus letter is, how that? far,

my ( $inp, $outp) = qw / out2 outfile/;  open $input, '<', $inp or die; open $output, '>', $outp or die;  ($last_key, $count);  while ( <$input> ) {  $key = join ' ', (split)[0..2]; $id = join ' ', (split)[7];  if ( defined $last_key , $key eq $last_key ) { ++$count; } else { printf "%s %d $id\n", $last_key, $count if defined $last_key; $last_key = $key; $count = 1; }  printf "%s %d $id\n", $last_key, $count if eof; } 

which gives :

1 1 1 3 b 2 2 2 2 b 

which isn't quite i'm aiming for.

thanks!

edit2

got wanted working. oftentimes, takes asking figure out yourself.

updated code:

my ( $inp, $outp) = qw / out2 outfile/;  open $input, '<', $inp or die; open $output, '>', $outp or die;  ($last_key, $count, $last_id);  while ( <$input> ) {  $key = join ' ', (split)[0..2]; $id = join ' ', (split)[7];  if ( defined $last_key , $key eq $last_key ) { ++$count; } else { printf "%s %d $last_id\n", $last_key, $count if defined $last_key; $last_key = $key; $count = 1; $last_id = $id; } printf "%s %d $id\n", $last_key, $count if eof; } 

on:

1 1 1 1 1 1 2 1 1 1 3 4 4 4 1 1 1 4 4 4 2 2 2 2 3 3 3 2 b 2 2 2 1 1 1 1 b 3 3 3 2 5 4 2 c 

gives:

1 1 1 3 2 2 2 2 b 3 3 3 1 c 

thanks all!

this matter of forming key first 3 fields , counting number of times occur, printing line of output whenever key changes or end of file reached

use strict; use warnings;  ($last_key, $count);  while ( <data> ) {    $key = join ' ', (split)[0..2];    if ( defined $last_key , $key eq $last_key ) {     ++$count;   }   else {     printf "%s -> %d\n", $last_key, $count if defined $last_key;     $last_key = $key;     $count = 1;   }    printf "%s -> %d\n", $last_key, $count if eof; }  __data__ 1 1 1 1 1 1 2 1 1 1 3 4 4 4 1 1 1 4 4 4 2 2 2 2 3 3 3 2 b 2 2 2 1 1 1 1 b 3 3 3 1 1 1 1 c 

output

1 1 1 -> 3 2 2 2 -> 2 3 3 3 -> 1 

update

to include final column in output data, change

my $key = join ' ', (split)[0..2] 

to

my $key = join ' ', (split)[0..2,-1] 

output

1 1 1 -> 3 2 2 2 b -> 2 3 3 3 c -> 1 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -