简体   繁体   中英

Perl : string of variable within a variable

Here is an example of what i'm trying to do: I want to "defined" a name for the input and then when it's taken into a function, only then it will substitute all the 3 variables.

$place_holder = 'f${file_case}_lalal_${subcase}_${test}';

.... somewhere else in another function:

read file containing 3 set of numbers on each line that represents the $file_case, $subcase, $test

while(<IN>){
   ($file_case, $subcase, $tset) = split;
   $input = $place_holder    #### line #3 here needs to fix
   print " $input \n";
}

Unfortunately, it prints out f${file_case} lalal ${subcase}_${test} for every single line. I want those variables to be substituted. How do I do that, how do I change line #3 to be able to output as i wanted ? I don't want to defined the input name in the subroutine, it has to be in the main.

You can do it using subroutines for example, if that satisfies your criteria

use warnings;
use strict;

my $place_holder = sub {
    my ($file_case, $subcase, $test) = @_;    
    return "f${file_case}_lalal_${subcase}_${test}";
}

# ...

while (<IN>) { 
    my ($file_case, $subcase, $tset) = split;
    #
    #  Code to validate input
    #
    my $input = $place_holder->($file_case, $subcase, $tset);
    print "$input\n";
}

I've used code reference with an anonymous subroutine in anticipation of uses that may benefit from it, but for the specified task alone you can use a normal subroutine as well.

Note that you have $test and $tset , which doesn't affect the above but may be typos.

You may use the String::Interpolate module, like this

use String::Interpolate 'interpolate';

my $place_holder = 'f${file_case}_lalal_${subcase}_${test}';


while ( <IN> ) {
    my ($file_case, $subcase, $test) = split;

    my $input = interpolate($place_holder);
    print "$input\n";
}

The module gives access to Perl's built-in C code that performs double-quote interpolation, so it is generally fast and accurate

Try eval while(<IN>){ ($file_case, $subcase, $tset) = split; $input = eval $place_holder #### line #3 here needs to fix print " $input \\n"; } while(<IN>){ ($file_case, $subcase, $tset) = split; $input = eval $place_holder #### line #3 here needs to fix print " $input \\n"; }

A while after I posted, I found a way to do it.

in the ## line 3, do this:

($input = $place_holder) =~ s/(\\${w+})/$1/eeg;

and everything works. Yes the above tset is a typo, meant to be test. Thank for everybody's response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM