Peter Stuifzand

Use named capture buffers to fill a hash

This is a small Perl 5.10 tip. You can use named capture buffers to fill a hash. Before 5.10 you needed to ‘unpack’ the values from a regex match into a hash.

I will give a small example that shows the problem this creates.

my $str = "name=value";
my %result;

if ($str =~ m/(\w+)=(\w+)/) {
    $result{name} = $1;
    $result{value} = $2;
}

The problem with this is that you need to number the variables and assign each individually to the hash. In Perl 5.10 you can do the following.

if ($str =~ m/(?<name>\w+)=(?<value>\w+)/) {
    %result = %+;
}

This is a lot simpler, cleaner and contains less possible bugs.

© 2023 Peter Stuifzand