Skip to content

Instantly share code, notes, and snippets.

@dhilst
Last active December 12, 2025 03:11
Show Gist options
  • Select an option

  • Save dhilst/dd613c4f588c47cfb10d6580e05c6f23 to your computer and use it in GitHub Desktop.

Select an option

Save dhilst/dd613c4f588c47cfb10d6580e05c6f23 to your computer and use it in GitHub Desktop.
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