How to create files with two or more variables in its names?

Hi all,
Iam writing a perl script to create many files with variables in their name.
i am able to do it, if iam using only one variable. But with two variables the file
names are NOT getting generated in the way i want.

plz help me out.

1. open(SHW,">divw_unsigned_50_50_$k.reset") or die $!;

output files generated:
divw_unsigned_50_50_0.reset    divw_unsigned_50_50_1.reset  divw_unsigned_50_50_2.reset   divw_unsigned_50_50_3.reset   

2. open(SHW,">divw_unsigned_$p_50_$k.reset") or die $!;

output files generated:
divw_unsigned_0.reset    divw_unsigned_1.reset 
divw_unsigned_2.reset   divw_unsigned_3.reset  

Here in 2nd case the numbers are the values of $k. But $p_50 is getting ignored. $p is some other variable whose value also varies.

You are actually using the variable "$p_50_" and this is most likely unset, so it contains an empty string.

I hope this helps.

bakunin

Try
${p_50} for variable p_50
${p} for variable p

open(SHW,">divw_unsigned_${p_50}_${k}.reset") or die $!;
1 Like

HI Thanks for reply,

$p is the value iam input iam reading

my $p = <STDIN>;
print "p: $p:;
open(SHW,">divw_unsigned_$p_50_$k.reset") or die $!;
print SHW "STICK divw_unsigned.cfg_32  ",  ($p==32)&1,  "\n";

I have added a print of $p and it is printing the value given in <STDIN>;
and iam using $p for some operation in the files created and that operation is working fine. Problem is with ONLY file names.

---------- Post updated at 04:27 PM ---------- Previous update was at 04:19 PM ----------

Thanks all for your quick reply.

open(SHW,">divw_unsigned_${p}_${i}_${k}.reset") or die $!;
or
open(SHW,">divw_unsigned_${p}_${i}_$k.reset") or die $!;
output files generated:
divw_unsigned_44_33_0.reset 
divw_unsigned_44_33_1.reset
divw_unsigned_44_33_2.reset
divw_unsigned_44_33_3.reset

both of these are working. But I want to know why? please educate me on this.

If you are mixing text and variable, always use curly bracket.
This way you are 100% sure what is variable or not.
$k. its ignoring the . and threats the variable as $k
$p_50 Here bash handles _ and 50 as part of variable name. So variable gets name $p_50 and not $p

k=2
echo "$k.tt"
2.tt

echo "$k_tt"
<nothing>

echo "${k}_tt"
2_tt
1 Like