Aaron Perry Aaron Perry - 1 year ago 58
Perl Question

Open Text File Using Variable in Filename

I am trying to open a text file in my perl script. Part of the filename contains the date in YYYYMMDD format, which changes. I am having problems building the file path correctly.

Full Filename:



use POSIX qw(strftime);
$currdate = strftime "%Y%m%d\n", localtime;

$filename = 'directory/', $currdate '_filename.txt';

open(FILE, $filename) or die "Cant find file";

Answer Source

A couple of things, you had \n in your strftime call, which appends a new line. You don't want this. You're not concatenating your string properly here:

$filename = 'directory/', $currdate '_filename.txt';

it's . not ,, and you don't have one between the variable and _filename.txt. The example below includes use strict; use warnings; and does what you want:

use strict;
use warnings;
use POSIX qw(strftime);

my $currdate = strftime( "%Y%m%d", localtime );
my $filename = 'directory/' . $currdate . '_filename.txt';
print $filename;

Edit, also use 3 argument open, and get it to tell you why it failed:

open(FILE,'<', $filename) or die "Cant find file $!\n";