* Ranga Nathan <[EMAIL PROTECTED]> [2002-10-11 13:42]:
> I need to parse a string that has multiple occurrences of a pattern
> that is determined by an embeded count. For example:
> 
> 02 s1n1 s1n2 3 s2n1 s2n2 s2n3 1 s3n1 4 s4n1 s4n2 s4n3 s4n4
> 
> 02 is the count and I need to extract s1n1 and s2n2
> 
> 3 is the count and  I need to extract s2n1, s2n2 and s2n3

Don't use a regex:

  my $s = "02 s1n1 s1n2 3 s2n1 s2n2 s2n3 1 s3n1 4 s4n1 s4n2 s4n3 s4n4";
  my @s = split /\s+/, $s;
  my @all = ();  # holds the answer

  while (@s) {
      my $num = shift @s;
      my @inner;         
      for (1 .. int($num)) {
          push @inner, shift @s
      }
      push @all, \@inner;
  }

  print Dumper(\@all);

Gives:

$VAR1 = [
          [
            's1n1',
            's1n2'
          ],
          [
            's2n1',
            's2n2',
            's2n3'
          ],
          [
            's3n1'
          ],
          [
            's4n1',
            's4n2',
            's4n3',
            's4n4'
          ]
        ];

$s is the original string, @s is the split string, and @all is the list.
You'll probably want to do something other thanb push @all and print
Dumper(), of course...

(darren)

-- 
In the fight between you and the world, back the world.
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to