#!/usr/bin/env perl -l use strict; use warnings; my $master = 'comp.hw.'; my @items = qw{ comp. comp.hw. comp.hw.new. comp.hw.hw. comp.sw.old. muse.hw.new. ancient. comp comp.hw comp.hw.new comp.hw.hw comp.sw.old muse.hw.new ancient }; for my $level (1 .. split /\./, $master, -1) { print "Match Level: $level"; my $re = '^' . join('\.' => (split /\./, $master, $level + 1)[0 .. $level - 1]); $re .= $re =~ /\.$/ ? '[^.]' : '(?:[.]|$)'; print "Matching: /$re/"; print "\t$_" for grep { /$re/ } @items; }