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

Hi, Below is my perl to read data from the text files... But, it can't print out any data from the input file. could some body give some ideas ...
#!/usr/bin/perl -w use strict; use Getopt::Std; my $prog = $0; $prog =~ s|.*/||; my %opts; getopts('o:', \%opts); my $cmd = $opts{o} || 1; my %wordDb = (); unshift (@ARGV, "-") unless @ARGV; for my $file (@ARGV) { open (IN, "< $file") or warn ("Can't open $file: $!\n"), die; my $data = $_; print ("$file ==> $data\n"); close(IN); }

Replies are listed 'Best First'.
Re: Can't print data from the input file in Command Line processing.
by Roger (Parson) on Dec 01, 2003 at 06:41 UTC
    You need to read from the file first!

    Method 1
    open (IN, "< $file") or warn ("Can't open $file: $!\n"), die; while (<IN>) { # loop through the file, print ("$file ==> $_"); # read one line at a time } close(IN);
    Method 2
    open (IN, "< $file") or warn ("Can't open $file: $!\n"), die; chomp(my @data = <IN>); # read all lines into array of lines # and get rid of trailing \n's print "$_\n" for @data; close(IN);
    Method 3
    open (IN, "< $file") or warn ("Can't open $file: $!\n"), die; my $data = do { local $/; <IN> }; # file slurping print ("$file ==> $data\n"); close(IN);
Re: Can't print data from the input file in Command Line processing.
by bbfu (Curate) on Dec 01, 2003 at 06:53 UTC

    Also note that you could make your main loop much simpler using the <> operator.

    #!/usr/bin/perl -w use strict; use Getopt::Std; my $prog = $0; $prog =~ s|.*/||; my %opts; getopts('o:', \%opts); my $cmd = $opts{o} || 1; my %wordDb = (); # Works exactly like your posted code is supposed to while(<>) { print "$ARGV ==> $_"; }

    bbfu
    Black flowers blossom
    Fearless on my breath