Perl如何通过循环从多个哈希构建指定格式字符串
用Perl循环生成指定格式字符串
初始代码
#!/usr/bin/env perl use warnings; use strict; my %hash_a = ( "num" => 7, "date" => 20221104, "prath" => "1.1.10", "antema" => "1.1.15" ); my %hash_b = ( "num" => 8, "date" => 20221105, "prath" => "1.1.16", "antema" => "1.1.19" ); my %hash_c = ( "num" => 9, "date" => 20221112, "prath" => "1.1.20", "antema" => "1.1.39" );
需求
希望通过循环生成如下格式的字符串,避免用循环构建变量名来获取hash_a、hash_b、hash_c这类技巧,习惯用类似Python多维数组的方式处理:
07_class_date_20221104_-_starting_verse_1.1.10_-_closing_verse_1.1.15.mp4 08_class_date_20221105_-_starting_verse_1.1.16_-_closing_verse_1.1.19.mp4 09_class_date_20221112_-_starting_verse_1.1.20_-_closing_verse_1.1.39.mp4
解决方案
在Perl中可以用数组存储哈希引用,实现和Python列表存字典一样的逻辑,直接循环处理即可:
#!/usr/bin/env perl use warnings; use strict; # 用数组存储所有数据的哈希引用 my @classes = ( { num => 7, date => 20221104, prath => "1.1.10", antema => "1.1.15" }, { num => 8, date => 20221105, prath => "1.1.16", antema => "1.1.19" }, { num => 9, date => 20221112, prath => "1.1.20", antema => "1.1.39" }, ); # 循环生成目标字符串 foreach my $class (@classes) { my $filename = sprintf( "%02d_class_date_%d_-_starting_verse_%s_-_closing_verse_%s.mp4", $class->{num}, $class->{date}, $class->{prath}, $class->{antema} ); print "$filename\n\n"; }
说明
- 把原来的三个独立哈希整合到数组
@classes中,每个元素是哈希引用,完全不需要拼接变量名,逻辑和Python的多维数组一致。 - 使用
sprintf的%02d格式化规则,确保num始终是两位数字(不足时前面补0)。 - 按需求拼接字符串并输出,结果和期望格式完全匹配。
内容的提问来源于stack exchange,提问作者user1850133
相关产品推荐
相关产品推荐

