#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @account = qw( 96329XY 7776fc 334457yg 2233oop 000001 8877666b); my @file = qw(8877666b.txt 2233oop.txt 334457yg.txt 7776fc.txt 96329XY_K.txt); my %seen; for my $acc (@account) { next unless $acc =~ /^\d+/; my $key = $acc; push @{$seen{$key}}, $acc; } #print Dumper %seen; for my $filename (@file) { next unless $filename =~ /^\d+/; my $key = $filename; ... }