perl,从多个变量内容构建字符串

dm7nw8vv  于 2022-11-24  发布在  Perl
关注(0)|答案(2)|浏览(135)

我的出发点是:

#!/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

08_class_date_20221112_-_starting_verse_1.1.20_-_closing_verse_1.1.39.mp4
xcitsw88

xcitsw881#

我认为你的问题更多的是关于变量的循环,而不是关于构建字符串。
通常,您不会创建一组单记录哈希值,然后尝试对它们进行循环,就像您对%hash_a%hash_b等所做的那样。我会将它们都放在一个结构中,在本例中是一个数组:

my @all = (
{ 
    "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" 
});

然后,您可以简单地循环数组:

for my $record (@all) {
   my $num = $record->{num}; # etc...

sprintf构建字符串

wgmfuz8q

wgmfuz8q2#

以下是一个示例:

use feature qw(say);
use strict;
use warnings;
use experimental qw(declared_refs refaliasing);

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"
);

sub get_str {
    my \%hash = $_[0];

    sprintf "%02d_class_date_%s_-_starting_verse_%s_-closing_verse_%s.mp4",
      $hash{num}, $hash{date}, $hash{prath}, $hash{antema};
}

for my $ref (\%hash_a, \%hash_b, \%hash_c) {
    my $str = get_str($ref);
    say $str;
}

输出

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

相关问题