#!/usr/bin/perl use strict; use warnings; sub get_etc_passwd { open(my $fh, '<', '/etc/passwd') or die $!; return <$fh>; } my @ids = qw( john james ); my @etc_passwd = get_etc_passwd(); { my $pattern = join('|', map quotemeta, @ids); my $re = qr/^(?:$pattern)/; print(grep /$re/, @etc_passwd); } { my $pattern = join('|', map quotemeta, @ids); # Assumes each of @ids match /^\w/ and /\w\z/. my $re = qr/\b(?:$pattern)\b/; print(grep /$re/, @etc_passwd); }