Reputation: 435
I have info contained in a variable that I need to have written to a file. My script needs to be create the file and then write to it.
Here's my current script:
my $file_location = '/network/$custom_directory/$custom_filename';
open(my $file ">", $file_location) or die $!;
print $file "$variable_data";
close $file;
I'm getting the feeling that my script is getting hung up on the actual file creation, rather than the variable-writing process. The error I get when I run the script is: 'No such file or directory' at the line where I try to open the file.
Upvotes: 1
Views: 13709
Reputation: 80384
You didn’t say what your error is.
Which gives you something like this, with obligatory preamble:
#!/usr/bin/perl
use strict;
use warnings;
my $custom_directory = "something old";
my $custom_filename = "something new";
my $data = "something borrowed";
my $path = "/network/$custom_directory/$custom_filename";
open(my $handle, ">", $path) || die "can't open $path: $!";
binmode($handle); # for raw; else set the encoding
print $handle "$data\n";
close($handle) || die "can't close $path: $!";
Upvotes: 4
Reputation: 241868
You have a syntax error in your programme. All three arguments of open
must be separated by commas.
open my $file, '>', $file_location or die $!;
Single quotes do not interpolate, unlike double quotes, so you probably need them in the file path:
my $file_location = "/network/$custom_directory/$custom_filename";
BTW: Including a sole variable into double quotes server no purpose for string contents. You can equivalently
print $file $variable_data;
Upvotes: 9
Reputation: 13792
First,
use strict;
use warnings;
may help. Second, variable interpolation requires double quoted strings:
my $file_location = "/network/$custom_directory/$custom_filename";
Third, you may probably need a \n at the print statement:
print $file "$variable_data\n";
And finally, your open statement should be:
open my $file, ">", $file_location or die $!;
Upvotes: 3
Reputation: 98746
Two things: First the file location is in single-quotes, so the $
variables won't be interpolated. Second, you're missing a comma in the call to open
. The code should read:
my $file_location = "/network/$custom_directory/$custom_filename";
open(my $file, ">", $file_location) or die $!;
Upvotes: 3