Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

open fails to open file when filename read from STDIN

by Nicpetbio23! (Acolyte)
on Jul 09, 2017 at 17:20 UTC ( [id://1194622]=perlquestion: print w/replies, xml ) Need Help??

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

Why doesn't this read my file into the array properly? How can I fix it

-----------------------------------------------------------------------

print "Please enter id file\n"; my $file = <STDIN>; open (my $handle, '<',$file); chomp (my @lines = <$handle>); close $handle;

Replies are listed 'Best First'.
Re: open fails to open file when filename read from STDIN
by LanX (Saint) on Jul 09, 2017 at 17:31 UTC
    I think you need to chomp $file too.

    in any case you need to check for errors from open:

    open(my $fh, "<", "input.txt")    or die "Can't open < input.txt: $!";

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Re: open fails to open file when filename read from STDIN
by hippo (Bishop) on Jul 09, 2017 at 21:04 UTC
      Plus number 2 (and 3). :)
Re: open fails to open file when filename read from STDIN
by Anonymous Monk on Jul 09, 2017 at 17:29 UTC
    There's a newline on the end of the filename, which you need to get rid of. Also, always error-check your opens.
    my $file = <STDIN>; chomp $file; open my $handle, '<', $file or die "Can't read $file: $!";
Re: open fails to open file when filename read from STDIN
by karlgoethebier (Abbot) on Jul 10, 2017 at 09:30 UTC

    TMTOWTDI with the error handling for free:

    #!/usr/bin/env perl use strict; use warnings; use Path::Tiny; use Data::Dump; use feature qw(say); say q(Please enter id file); chomp( my $file = <STDIN> ); my @data = path($file)->lines( { chomp => 1 } ); dd \@data; __END__

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1194622]
Approved by marto
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-04-23 06:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found