G'day anandk,
Welcome to the Monastery.
"$hash{/abc_(.*)_ghi/} = boom_$1"
There's all sorts of problems with that; let's step through them.
$ perl -wE 'use Data::Dump; my %h; dd \%h; $_ = "a_b_c"; $h{/a_(.*)_c/
+} = boom_$1; dd \%h'
{}
Can't call method "boom_" on an undefined value at -e line 1.
So the RHS (right-hand side) would need to be quoted.
$ perl -wE 'use Data::Dump; my %h; dd \%h; $_ = "a_b_c"; $h{/a_(.*)_c/
+} = "boom_$1"; dd \%h'
{}
Use of uninitialized value $1 in concatenation (.) or string at -e lin
+e 1.
{ 1 => "boom_" }
In scalar context (between the braces in $h{...})
you'll only count the number of captures (1 in this case),
as opposed to returning the captured values.
You'd need to supply a list context.
$ perl -wE 'use Data::Dump; my %h; dd \%h; $_ = "a_b_c"; $h{(/a_(.*)_c
+/)[0]} = "boom_$1"; dd \%h'
{}
Use of uninitialized value $1 in concatenation (.) or string at -e lin
+e 1.
{ b => "boom_" }
So, now we have the key (b in this case)
but $1, in "boom_$1", is not initialised.
The problem here is that the RHS of an assignment is evaluated before the LHS (left-hand side).
The capture (to $1) occurs on the LHS, so $1 is not available when the RHS is evaluated.
You don't actually want "b" as a key and trying to write your code like that
clearly isn't going to work anyway. So, abandon that idea.
If you add a cross-reference table and use a less specific regex, you can actually do this in one statement.
You've been less than precise with exactly what you want.
You mentioned "4 key-value pairs",
but show a hash with eight and regexes to match six of them:
this doesn't help us to provide a concrete solution.
It's also unclear what the significance is of the leading and trailing parts of the keys;
for instance, do all keys that start with "abc", end with "ghi"?
are there other variations?
if so, should they be handled differently?
Because of all unknowns surrounding your question,
consider the following code as a technique that you can adapt for your needs rather than a solution.
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dump;
my %hash = (
xxx_text10_yyy => 1,
xxx_text11_yyy => 1,
mmm_text12_nnn => 1,
mmm_text13_nnn => 1,
abc_text6_ghi => 1,
abc_text7_ghi => 1,
abc_text8_ghi => 1,
abc_text9_ghi => 1
);
my %xref = (
abc => 'boom',
mmm => 'doom',
xxx => 'zoom',
);
my $re = qr{(?x: ^ ( [^_]+ ) _ ( [^_]+ ) )};
/$re/ and $hash{$_} = join '_', $xref{$1}, $2 for keys %hash;
dd \%hash;
Output:
{
abc_text6_ghi => "boom_text6",
abc_text7_ghi => "boom_text7",
abc_text8_ghi => "boom_text8",
abc_text9_ghi => "boom_text9",
mmm_text12_nnn => "doom_text12",
mmm_text13_nnn => "doom_text13",
xxx_text10_yyy => "zoom_text10",
xxx_text11_yyy => "zoom_text11",
}
|