Arbariya has asked for the wisdom of the Perl Monks concerning the following question:

hello, i have this code but when i run this is gives me the following errors can any one tell me why this error is there
Unsuccessful stat on filename containing newline at 5.pl line 11, <STDIN> line 1
. Unsuccessful stat on filename containing newline at 5.pl line 26, <STDIN> line 1
use strict; use warnings; use POSIX qw(strftime); print ("enter file name"); my $filename =<STDIN>; print $filename; if(-d $filename) { warn "File is direcrtory\n"; $filename = strftime "foo.%Y%m%d-%H%M%S.txt", localtime; print "A good filename could be '$filename'"; } else { print "File is not a directory"; #Check if file is already existing # if(-e $filename) #Overwriting an already existing file # { open(NEWFH,">$filename") || die "$filename: $!"; } }

janitored by ybiC: Balanced <code> tags around codeblock instead of HTML formatting

Replies are listed 'Best First'.
Re: name the file with current date and time
by Corion (Patriarch) on Mar 03, 2005 at 10:45 UTC

    In the CB I already mentioned the modules POSIX, DateTime and Time::Piece to you, all of which supply the strftime function. What problem do you have that is not solved by the strftime function?

    Example code:

    use strict; use POSIX qw(strftime); my $filename = strftime "foo.%Y%m%d-%H%M%S.txt", localtime; print "A good filename could be '$filename'"
Re: name the file with current date and time
by holli (Abbot) on Mar 03, 2005 at 10:46 UTC
    Simply use strftime:
    use strict; use POSIX qw(strftime); my $name = strftime ("%Y%m%d-%H%M%S", localtime);
    more about this here.


    holli, /regexed monk/
Re: problem with naming the file with current date and time
by gellyfish (Monsignor) on Mar 03, 2005 at 13:44 UTC
Re: problem with naming the file with current date and time
by Crackers2 (Parson) on Mar 03, 2005 at 20:04 UTC

    The filename you get from my $filename=<STDIN> has a newline at the end. You need to remove this, for example by doing a chomp $filename.

Re: problem with naming the file with current date and time
by minter (Novice) on Mar 03, 2005 at 21:11 UTC

    The warning is telling you that your filename contains a newline. That's because when you do  my $filename =<STDIN>;, it's including the newline that's generated when you press Enter.

    So when you see: enter file name

    And you do myfile<ENTER>

    $filename gets "myfile\n" as its contents. If you chomp() $filename, that will get rid of the newline in the variable, and as such the error. So you could do: chomp( my $filename = <STDIN> )

    to fix it.