olivierg olivierg - 4 years ago 101
Perl Question

generate 'next ifs' from config file in Perl

there is something in Perl I don't know how to code, can I request your help please.

basically, I'm trying to use a configuration file with an array (or a hash or anything of that sort) containing "exceptions" that I want to use in a "next if" of a loop of the main program.

exemple :

my program looks like that :

while(<>) {
next if /regex1/;
next if /regex2/;
next if /regexN/;

and I want to be able to put these "next if" from a config file, like :

my %conf = do './config_file.conf';
while(<>) {
# put code here to add all 'next ifs';

config file example :

exceptions => [

how can I do this easily in my code ? (where the comment is, that is, adding all "next if" from an array

thanks !

Answer Source

You can use a another loop to iterate over all your patterns inside of your while. If you assign a label to your while loop you can next that directly.

my %conf = ( exceptions => [ 'regex1', 'regex2', 'regexN', ], );

OUTER: while (<DATA>) {
    foreach my $re (@{ $conf{exceptions} }) {
        next OUTER if m/$re/;


This will output


Note that the do './config_file.conf' is very safe. You should use a module to read a config file format instead. That will make your code more portable and make sure no code you might not control gets executed. For example, you could use JSON, or Config::Simple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download