#!/usr/bin/perl -w use strict; use Data::Dumper; my $dict = {}; while () { chomp; insert($_); }; sub insert { my @chars = split '', shift; my $len = - scalar @chars; my $curr = $dict; while (@chars) { my $char = shift @chars; if (! exists $curr->{$char}) { $curr->{$char} = {} }; $curr = $curr->{$char}; }; $curr->{''} = $len; }; # print Dumper $dict; my $str = 'owijfwapplelaskfiwejfcherryalkfwiofwfblossomowiejfbeetl'; my $pos = 0; my @running; while ($pos < length $str) { my $char = substr( $str, $pos, 1 ); push @running, $dict; for my $word (@running) { if (exists $word->{''}) { print "Found ", substr( $str, $pos + $word->{''}, - $word->{''} ), "\n"; }; if (exists $word->{$char}) { $word = $word->{$char}; } else { undef $word; }; }; @running = grep { defined } @running; $pos++; }; __DATA__ apple blossom cherry blouse bar bee beetle