如何使用$ 1,$ 2,$ 3动态分配哈希值

use*_*005 6 regex perl eval

我想动态创建一个%detail哈希,而不使用eval语句.这段代码可以正常使用eval语句,但有没有更好的方法来执行此操作而不使用eval

my @input=('INFO: Vikram 32 2012','SAL: 12000$','ADDRESS: 54, junk, JUNK');

my %matching_hash= (
                    qr/^INFO:\s*(\S+)\s+(\S+)\s+(\S+)/ =>['name','age','joining'],
                    qr/^SAL:\s*(\S+)/ => ['salary'],
                    qr/ADDRESS:\s*(.*)/ =>['address']
                    );
my %detail;
while(my ($regex, $array) = each(%matching_hash)) {
    foreach (@input){
        if(/$regex/) {
            for(my $i=0;$i<=$#$array; $i++) {
                $j=$i+1;
                eval '$detail{$array->[$i]} = $$j';
            }
        }
    }
}
use Data::Dumper;

print Dumper(\%detail);
++++++++++++++

$VAR1 = {
          'name' => 'Vikram',
          'address' => '54, junk, JUNK',
          'age' => '32',
          'joining' => '2012',
          'salary' => '12000$'
        };
Run Code Online (Sandbox Code Playgroud)

per*_*eal 14

相关部分:

if(my @m = /$regex/) {
  for(my $i=0;$i<=$#$array; $i++) {
      $detail{$array->[$i]} = $m[$i];              
  }   
}   
Run Code Online (Sandbox Code Playgroud)


Tot*_*oto 5

更改for循环:

for(my $i=0;$i<=$#$array; $i++) {
    $j=$i+1;
    eval '$detail{$array->[$i]} = $$j';
}
Run Code Online (Sandbox Code Playgroud)

通过:

@detail{@{$array}} = ($_ =~ $regex);
Run Code Online (Sandbox Code Playgroud)