First turn on strictures (you always use strictures don't you?), then set up the target string and the search list. Perform the search using the starting parameters.

use strict; use warnings; my $target = "cowboycatdog"; my @parts = qw(cow cowboy boy cat at do dog); search ($target, [@parts], []);

Assign the parameters passed to the sub to local variables. Note that the arrays are passed as references so that two arrays can be passed.

sub search { my ($target, $parts, $used) = @_;

Check to see if there is anything left to match. If the target string is zero length then we have a successful combination in @$used. Print the result and return.

unless (length $target) { print join ("-", @$used), "\n"; return; }

otherwise loop over the remaining unused words looking for matches with the start of the remaining target string.

for my $part (@$parts) {

if there is no match for the current word at the start of the target string skip to the next word

next unless 0 == index $target, $part;

otherwise isolate the part of the target string following the current word.

my $remainder = substr $target, length $part;

Recursively search the remaining part of the target string using the word list passed in excluding the current word and passing a list of the words used so far plus the current word.

search ($remainder, [grep {$part ne $_} @$parts], [@$used, $pa +rt]); } }

Perl is environmentally friendly - it saves trees

In reply to Re^2: combining array items to match a certain string by GrandFather
in thread combining array items to match a certain string by pc2

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.