Samss77
Samss77

Reputation: 15

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

Upvotes: 0

Views: 1128

Answers (3)

Sinan Ünür
Sinan Ünür

Reputation: 118138

The question is whether you need the intermediate array, and the three extra variables. If not, you can write the whole thing as:

my $memfilename = sprintf(
    '%s_%s_%s.txt',
    split(/[.]/, $line, 3), # whether you want 3 here depends on your input
);

If you do need the three intermediate variables, you can still skip the creation of the @value array and write something more legible than interpolating three variables into a string:

my ($fpga_name, $block_name, $mem_name) = split /[.]/, $line, 3;
my $memfilename = sprintf '%s_%s_%s.txt', $fpga_name, $block_name, $mem_name;

Using sprintf yields code that is much more readable than interpolating three variables, the braces, the underscores, the sigils etc.

Alternatively, you could also use:

 my $memfilename = sprintf '%s.txt', join('_', split /[.]/, $line, 3);

Again, whether you want the third argument to split depends on your input.

Finally, if you find yourself doing this in more than one place, it would help to put it in a function

sub line_to_memfilename {
    my $line = shift;
    # ...
    return $memfilename;
}

so if the format ever changes, you only need to make the change in one place.

Upvotes: 1

jwodder
jwodder

Reputation: 57500

Indicate where the variable names begin & end by writing ${varname}:

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

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61510

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

Upvotes: 2

Related Questions