in reply to Re: Searching for a string within an array using regex
in thread Searching for a string within an array using regex

use warnings; use strict; use List::Util qw/first/; my %INDEX_PAGE = map {$_=>1} '/','/index.html'; my @HELP_PAGE = map {qr/^\Q$_\E/} '/help.html'; my @line_entry = ('/help.html','/index.html','/help.html?ri=all'); for my $le (@line_entry) { if (exists $INDEX_PAGE{$le}) { print "$le is an index page\n" } elsif (first {$le=~$_} @HELP_PAGE) { print "$le is a help page\n" } else { print "$le is unknown\n" } } # Output: # /help.html is a help page # /index.html is an index page # /help.html?ri=all is a help page

How many "pages" do you have? Because if it's more than a few, your code is still going to get very repetitive, and an even more general-purpose solution will probably be more maintainable in the long run.

Replies are listed 'Best First'.
Re^3: Searching for a string within an array using regex
by Anonymous Monk on Aug 14, 2014 at 18:14 UTC

    Improvement: The brute-force search of the regular expressions is actually not needed; one can just precompile the whole thing as one regular expression. (If you wanted to generalize even more, the same thing could be done for the index pages as well.)

    use warnings; use strict; my %INDEX_PAGE = map {$_=>1} '/','/index.html'; my $HELP_PAGE = join '|', map {quotemeta} '/help.html'; $HELP_PAGE = qr/^(?:$HELP_PAGE)/; my @line_entry = ('/help.html','/index.html','/help.html?ri=all'); for my $le (@line_entry) { if (exists $INDEX_PAGE{$le}) { print "$le is an index page\n" } elsif ($le=~$HELP_PAGE) { print "$le is a help page\n" } else { print "$le is unknown\n" } }