T
tickfigure
Hello,
I've inherited some code and have to make a few changes. I'm sure this is
not the way to go about this.... Hopefully someone can help me.
I'm trying to generate the number of "captures" (variables $1, $2, etc.)
of a regex dynamically. I don't know how many are required. I've included
a small example below, so it is hopefully easier to understand.
Thanks for any help!
tick
#! /usr/bin/perl
use strict;
my %caphash = (
test1 => {
a => "1",
b => "1",
c => "1",
},
test2 => {
a => "1",
b => "1",
c => "1",
}
);
my %hashresult;
my %hash1;
my $string = "another string here";
my $pattern = '(\S+)\s+(\S+)\s+(\S+)';
my $caps = 3; # Because there are three capturing parenths in $pattern.
This variable
# exists purely for this example.
foreach my $ele (keys %caphash) { # foreach no.1
my $test = $caphash{$ele};
%hash1 = %$test;
foreach my $ele2 (keys %hash1) { # foreach no.2
# Here lies the problem.. since $pattern will change after each
# complete iteration of foreach no.1, the number of "captures" will
also change.
# (I have only included 1 pattern for the example.)
# How can I dynamically create the $1, $2, variables so that no
# matter how many "captures" the values will be inserted into the hash
# properly?
# This obviously does not work.
for (my $x = 1; $x <= $caps; $x++) {
$string =~ /$pattern/;
$hashresult{$ele}{$ele2} = $x;
}
}
}
print "End\n";
I've inherited some code and have to make a few changes. I'm sure this is
not the way to go about this.... Hopefully someone can help me.
I'm trying to generate the number of "captures" (variables $1, $2, etc.)
of a regex dynamically. I don't know how many are required. I've included
a small example below, so it is hopefully easier to understand.
Thanks for any help!
tick
#! /usr/bin/perl
use strict;
my %caphash = (
test1 => {
a => "1",
b => "1",
c => "1",
},
test2 => {
a => "1",
b => "1",
c => "1",
}
);
my %hashresult;
my %hash1;
my $string = "another string here";
my $pattern = '(\S+)\s+(\S+)\s+(\S+)';
my $caps = 3; # Because there are three capturing parenths in $pattern.
This variable
# exists purely for this example.
foreach my $ele (keys %caphash) { # foreach no.1
my $test = $caphash{$ele};
%hash1 = %$test;
foreach my $ele2 (keys %hash1) { # foreach no.2
# Here lies the problem.. since $pattern will change after each
# complete iteration of foreach no.1, the number of "captures" will
also change.
# (I have only included 1 pattern for the example.)
# How can I dynamically create the $1, $2, variables so that no
# matter how many "captures" the values will be inserted into the hash
# properly?
# This obviously does not work.
for (my $x = 1; $x <= $caps; $x++) {
$string =~ /$pattern/;
$hashresult{$ele}{$ele2} = $x;
}
}
}
print "End\n";