Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Array within regexp?

by jfrm (Monk)
on Feb 27, 2012 at 07:36 UTC ( #956390=perlquestion: print w/replies, xml ) Need Help??

jfrm has asked for the wisdom of the Perl Monks concerning the following question:

Oh peaceful ones, I have an array @titles = qw/Mr Mrs Ms Miss Dr Sir Lord Lady Rev/; To avoid the darkness of repetition and exult the glory of elegance, I would like to use it in the following regexp instead of retyping all the array elements: $text =~ /^(Mr|Mrs|Ms|Miss|Sir|Lord|Lady|Dr|Rev)\s+(.*)/) Please can anyone empower me with the knowledge?

Replies are listed 'Best First'.
Re: Array within regexp?
by davido (Cardinal) on Feb 27, 2012 at 07:40 UTC

    Introducing join.

    my @titles = qw/ Mr Mrs Ms Miss Dr Sir Lord Lady /; $alt_titles = join '|', @titles; if( $text =~ m/^($alt_titles)\s+(.*)/ ) { print "$1 => $2\n"; }


      Correct. However, if you mean the array to contain plain strings you want to match literally, you need to tell that to perl, otherwise it will try to interpret them as regexen, such as interpretting dots in the strings to match any character.

      $alt_titles = join '|', map quotemeta, @titles;

        Thanks for your good answers - I didn't think that would be so easy!

Re: Array within regexp?
by johngg (Canon) on Feb 27, 2012 at 10:06 UTC

    Another way is to change the default list separator to the pipe symbol and interpolate the array into a compiled regular expression.

    my @titles = qw{ Mr Mrs Ms Miss Dr Sir Lord Lady }; my $titlesRegex = do{ local $" = q{|}; qr{^(@titles)\s+(.*)} }; if( $text =~ $titlesRegex ) { print qq{$1 => $2\n}; }



Re: Array within regexp?
by Anonymous Monk on Feb 27, 2012 at 15:09 UTC
    ... or just stuff the thing "out of sight out of mind" like Regexp::Common does ... write it in a very simple way one time and refer to it everywhere else you need to use it. You do NOT want to look at the source-code of any of those CPAN modules, and fortunately you don't have to. When someone invents a new honorific you can change your code then.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://956390]
Approved by davido
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2022-06-27 06:10 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (86 votes). Check out past polls.