Skip to content

Instantly share code, notes, and snippets.

@sebkirche
Last active December 19, 2015 08:38
Show Gist options
  • Save sebkirche/5926600 to your computer and use it in GitHub Desktop.
Save sebkirche/5926600 to your computer and use it in GitHub Desktop.
Perl sample that illustrate the usage of (duplicated) named subpatterns
use v5.10.01;
use strict;
use warnings;
my $rx =
qr{
# match contain groups 'file' + 'line'
\bfile:? (?<file>.+) \s at \s line \s (?<line>\d+)
# match contain only 'line'
| \s at \s line \s (?<line>\d+)
# match contain only 'file'
| \bfile:? (?<file>.+)
}x;
my @test_data = (
# file + line
'importing file: c:/titi/toto/tutu.tata at line 42 : unknown error!',
# file only
'importing file: c:/titi/toto/tutu.tata.',
# line only
'error at line 101 : missing EOL!',
);
foreach my $data ( @test_data ){
say "data: ", $data;
if($data =~ /$rx/){
# the hash %+ contain named groups of the last regex match.
say "\tfile: ", $+{file} if $+{file};
say "\tline: ", $+{line} if $+{line};
}
else{
say "\tno match!";
}
}
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment