Created
April 26, 2017 12:05
-
-
Save pjf/2b8b5aa95d2492f4e84e0121268c736f to your computer and use it in GitHub Desktop.
Here are great things you can do with regexp matching groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# These lines enable newer Perl features (like 'say'), and encourage | |
# good coding practices. | |
use v5.10; | |
use strict; | |
use warnings; | |
use autodie; | |
# Our script will search for strings in the following form: | |
# "Transferred \$100 from 123456 to 532342 on 2017-03-01" | |
# We can have named matches inside regexp fragments. They have the same name | |
# as the variable which contains them, so we always know what they're called. | |
my $money = qr{(?<money> \$\d+) }x; | |
my $acct = qr{(?<acct> \d{6}) }x; | |
my $date = qr{(?<date> \d{4}-\d{2}-\d{2}) }x; | |
# Here's our actual regexp we want to match. It reads like an English sentence, | |
# and is super-easy to maintain! | |
my $transaction_re = qr{Transferred $money from $acct to $acct on $date}; | |
# This is Perl's way of saying "read from a file, or from stdin if there are no | |
# files mentioned on the command line. | |
while (<>) { | |
# If our regular expression matches, our match vars will be set. | |
if (/$transaction_re/) { | |
# $+{date} gives us the *last* date captured (of which there's only one). | |
# $-{acct}[0] and $-{acct}[1] gives us the 0th and 1st matches of acct. | |
say "$+{date}: $-{acct}[0] → $-{acct}[1] ($+{money})"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment