string - 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
}
解决方案
首先,您需要将名称拆分为 4 个部分:
my ($first, $second, $third, $fourth) = unpack("(A3)*", $name);
填充哈希
$hash{"first"} = $first;
$hash{"second"} = $second;
$hash{"third"} = $third;
$hash{"fourth"} = $fourth;
并打印哈希
print $hash{"fourth"};
推荐阅读
- testing - 环回运行状况真正检查的是什么?
- java - 如何为多个 Jbutton 编写动作监听器
- python - 使用字符串作为字节
- amazon-web-services - Snowflake 无法在没有访问密钥的情况下从 S3 下载文件,而 s3fs 能够从 S3 下载该文件
- amazon-web-services - 如何将全局变量放入 AWS sam 项目中
- javascript - Cloud Functions - 使用全局变量
- uwp - UWP App 中的 IdentityModel.OidcClient 从 3.1.2 迁移到 4.0
- typo3-10.x - TYPO3 Gridelements 10 - Gridelement Link Wizard Flexform
- neo4j - 获取neo4j中最重要的节点
- python-3.x - 如何使 python functools.lru_cache 返回值不可变?