Home > Software engineering >  perl, build strings from several variables content
perl, build strings from several variables content

Time:11-23

Here is my starting point:

#!/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" );

from this I want to make these strings using a loop, if possible without using any trick like building variable names through a loop to get 'hash_a', 'hash_b', 'hash_c'. I was used to use multidimensional arrays for such things in 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

CodePudding user response:

I take it your question is more about looping over the variables, and not so much about building the string.

Usually you would not make a bunch of one record hashes and then try to loop over them, like you are doing with %hash_a, %hash_b etc. I would put them all in a single structure, in this case an array:

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

Then you can simply loop over the array:

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

And build your string with sprintf

CodePudding user response:

Here is an example:

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 "d_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;
}

Output:

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
  •  Tags:  
  • perl
  • Related