Search code examples
perlvariablesfilenames

Perl use variable as a file name


How to create a file with name containing variables with underscore between them. I need to create a file with name like this $variable1_$vraiable2_$variable3.txt

@values=split(/\./, $line)
my $fpga_name=$values[0];
my $block_name=$values[1];
my $mem_name=$values[2];
my $memfilename="mem_init/$fpga_name_$block_name_$mem_name.txt";
open(WRITE_MEM_FILE, ">>memfilename");
print WRITE_MEM_FILE "$line \n";

Solution

  • You can simply wrap all of the variables in curly braces:

    my $memfilename="mem_init/${fpga_name}_${block_name}_${mem_name}.txt";
    

    Keep in mind you need a $ before memfilename in your open statement, otherwise you will just get the literal string:

    open(WRITE_MEM_FILE, ">>$memfilename");