Note: I'm not going to bother testing these because I'm just illustrating an approach. In essence, is $l1 an ordered subset of $l2?
use List::MoreUtils qw( all first_index indexes ); # Is $l1 in $l2? It's kinda a bit destructive. sub in_list { my ($l1, $l2) = @_; my $head = shift @$l1; my $head_idx = first_index { $head eq $_ } @$l2; return unless defined $head_idx; # Make sure $l2 is still big enough to hold $l1 return unless $#$l2 - $head_idx >= $#$l1; return all { $l1->[$_] eq $l2->[$_ + $head_idx] } indexes @$l1; }
The best solution, however, will allow for an optional equality test. You never know what kind of things are in those arrays. Oh, and we shouldn't be destructive.
sub in_list { my ($l1, $l2, $comp) = @_; $comp ||= sub { $_[0] eq $_[1] }; my $head = $l1->[0]; my $head_idx = first_index { $comp->($head,$_) } @$l2; return unless defined $head_idx; # Make sure $l2 is still big enough to hold $l1 return unless $#$l2 - $head_idx >= $#$l1 - 1; # It might be cheaper to re-compare the head elements. But, since +$comp is potentially # client-defined, we'd best not assume anything. $comp might not e +ven be side-effect # free!! *gasps* return all { $comp->($l1->[$_ + 1], $l2->[$_ + $head_idx]) } grep +{ $_ } indexes @$l1; }

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

In reply to Re: sublist of a list by dragonchild
in thread sublist of a list by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.