in reply to how extract and group data in a array

I'm not aware of any module to do this.

I don't see how "recursion" would help you here.

There's no need for an "ugly" loop. Just iterate your array; use a boolean flag to indicate if elements are in the wanted group.

#!/usr/bin/env perl -l use strict; use warnings; my @dd = qw/AA JJ CC M 1 1 3 4 D JJ 1 1 D M 3 3 4 D C M 3 3 3 D P Z/; my $in_group = 0; my (@group, @all_groups); for (@dd) { $in_group = 1 if $_ eq 'M'; next unless $in_group; push @group, $_; if ($_ eq 'D') { push @all_groups, [ @group ]; @group = (); $in_group = 0; } } print "@$_" for @all_groups;

Output:

M 1 1 3 4 D M 3 3 4 D M 3 3 3 D

— Ken

Replies are listed 'Best First'.
Re^2: how extract and group data in an array
by Athanasius (Archbishop) on Feb 21, 2017 at 07:45 UTC

    Nice. For the record, this can be simplified a little using Perl’s range operator in static context:

    use strict; use warnings; my @dd = qw/AA JJ CC M 1 1 3 4 D JJ 1 1 D M 3 3 4 D C M 3 3 3 D/; my @group; for (@dd) { if ($_ eq 'M' .. $_ eq 'D') # or: if (/^M$/ .. /^D$/) { push @group, $_; } elsif (@group) { print join(' ', @group), "\n"; @group = (); } } print join(' ', @group), "\n" if @group;

    Output:

    17:41 >perl 1752_SoPW.pl M 1 1 3 4 D M 3 3 4 D M 3 3 3 D 17:42 >

    Hope that’s of interest,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^2: how extract and group data in a array
by Anonymous Monk on Feb 21, 2017 at 07:18 UTC
    yeah, your way is the first into my mind, set status variable, store data into an array etc. but since the data in array is a bit like html/xml, I thought someone would write module to do this.....
      "... but since the data in array is a bit like html/xml, I thought someone would write module to do this....."

      If @dd was only intended as example data, and your real data is HTML or XML, then there are modules for that (which would probably be a better choice than reinventing the wheel and writing your own parsing code). Try http://search.cpan.org/ and look for modules in the HTML:: or XML:: namespaces.

      — Ken