Last active
December 12, 2025 03:11
-
-
Save dhilst/dd613c4f588c47cfb10d6580e05c6f23 to your computer and use it in GitHub Desktop.
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
| use strict; | |
| use warnings; | |
| use feature 'say'; | |
| use Data::Dumper; | |
| use Test::More; | |
| use Scalar::Util qw(looks_like_number); | |
| sub grep_str { | |
| my $lines = shift; | |
| my %acc; | |
| # accumualtes all grouped matches over %acc | |
| for my $line ($lines->@*) { | |
| # %acc = (%acc, ...) updates %acc with ... | |
| # %+ is the named groups mached with =~ | |
| %acc = (%acc, map { $line =~ $_ ? %+ : () } @_); | |
| } | |
| return \%acc; | |
| } | |
| sub grep_file { | |
| my $file = shift; | |
| # patterns = @_ | |
| open my $fh, "<", $file | |
| or die "open $file: $!"; | |
| my %acc; | |
| for my $line (<$fh>) { | |
| %acc = (%acc, map { $line =~ $_ ? %+ : () } @_); | |
| } | |
| return \%acc; | |
| } | |
| my @content = split /\n/, <<"EOF"; | |
| foo: bar | |
| tar: zar | |
| tick: tack toe 2 | |
| EOF | |
| is_deeply( | |
| grep_str( | |
| \@content, | |
| qr/foo: (?<foo>\w+)/, | |
| qr/tar: (?<tar>\w+)/, | |
| qr/tick: (?<tack>\w+) (?<toe>\w+) (?<num>\d+)/), | |
| { | |
| foo => "bar", | |
| tar => "zar", | |
| tack => "tack", | |
| toe => "toe", | |
| num => 2, | |
| }); | |
| ok(looks_like_number( | |
| grep_file( | |
| "/proc/meminfo", | |
| qr/MemTotal:\s+(?<MemTotalKb>\d+)/ | |
| )->{MemTotalKb})); | |
| done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment