Arianule
Arianule

Reputation: 9043

creating a textfile in perl

I was hoping for some assistance as to how to create a textfile specifically in perl receiving the input from user.

print "\ndirectory has been changed";
print "\nDear user, please enter the name of the file you want to create ";

my $nameFile = <>;

open MYFILE, ">$nameFile" or die "couldn't open the file $!";

This will create a file although not a text file.

regards Arian

Upvotes: 1

Views: 1503

Answers (1)

TLP
TLP

Reputation: 67900

Update: I just realized you did not chomp your STDIN there, so you will have a newline attached to the end of your file name.

chomp $filename;

Should solve that particular hiccup with your file name.

The recommended way to use open is using three arguments, and a lexical filehandle. MYFILE is a global, with all the inherent drawbacks and benefits.

use autodie;  # will check important errors for you, such as open
open my $fh,      '>',               $namefile;
#    ^- lexical   ^- explicit mode   ^- filename separated from mode

print $fh "This is a textfile\n";   # put something in the file

Upvotes: 6

Related Questions