David Wright
David Wright

Reputation: 435

How to Write a Variable to File in Perl

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

Answers (4)

tchrist
tchrist

Reputation: 80384

You didn’t say what your error is.

  • But you’re missing a comma.
  • You also have the wrong quotes.
  • You also (probably) forgot the newline at the end.
  • And you forgot to check that the close succeeded lest your filesystem should have filled up.
  • You may have forgotten the binmode or the encoding.

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

choroba
choroba

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

Miguel Prz
Miguel Prz

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

Cameron
Cameron

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

Related Questions