首页 > 解决方案 > perl中如何将字符串转换为哈希表

问题描述

我有一个来自 for 循环的字符串:

@file = "/path/window/*_testing_42.csv";


foreach $file(@file) {


$name = $file=~ /(\w*)_testing_42/; #comes from file path
$name = 1$;
print $name; #prints G43B76P90T45

}

我需要这个字符串中的 4 个值(G43、B76、P90、T45)。我想将它们放入散列中,以便我可以具体引用每个值。但是,我尝试实现的哈希表代码不适用于我的预期目的:

 my %hash;



foreach $file(@file) {


    $name = $file=~ /(\w*)_testing_42/; #comes from file path
    $name = 1$;
    print $name; #prints G43B76P90T45



    my($first $second $third $fourth) = $name;
    $hash{"first"} = $first;
    $hash{"second"} = $second;
    $hash{"third"} = $third;
    $hash{"fourth"} = $fourth;

预期输出:

    print $fourth; #should print T45


    print $first; #should print G43
    print $third #should print  P90
}

标签: stringperlhash

解决方案


首先,您需要将名称拆分为 4 个部分:

my ($first, $second, $third, $fourth) = unpack("(A3)*", $name);

填充哈希

$hash{"first"} = $first;
$hash{"second"} = $second;
$hash{"third"} = $third;
$hash{"fourth"} = $fourth;

并打印哈希

print $hash{"fourth"};

推荐阅读