You can get the regex engine to do this for you. It should be very fast
I hope it's obvious that the regex pattern needs to be built only once, and can then be used to find the longest prefix for any number of target strings
use strict;
use warnings;
use 5.010;
my @prefixes = qw/
1
121
12234
20345
21345
/;
my $target = 12134;
my $re = join '|', sort { length $b <=> length $a } @prefixes;
$re = qr/(?:$re)/;
say $1 if $target =~ /^($re)/;
output
121
Update
Alternatively, the Tree::Trie
module can be used to implement the trie search that the regex engine provides like this
use strict;
use warnings;
use 5.010;
use Tree::Trie;
my @prefixes = qw/
1
121
12234
20345
21345
/;
my $target = 12134;
my $trie = Tree::Trie->new({ deepsearch => 'prefix' });
$trie->add(@prefixes);
say scalar $trie->lookup($target);
The output, of course, is the same as that of the previous code