Ong Beng Seong
Ong Beng Seong

Reputation: 335

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.

Upvotes: 1

Views: 182

Answers (4)

Borodin
Borodin

Reputation: 126722

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

Upvotes: 2

Ong Beng Seong
Ong Beng Seong

Reputation: 335

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.

Upvotes: 0

zdim
zdim

Reputation: 66873

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.

Upvotes: 3

tuxuday
tuxuday

Reputation: 3037

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

Upvotes: -1

Related Questions