http://www.perlmonks.org?node_id=1023887


in reply to mac file problem

  1. You are not opening files properly.
  2. You don't seem to know how to read from a file.
  3. Why would you write a program that takes a location as input, when you can't even write a program to work with a hard coded location? Hint: you should NEVER write a program that takes ANY user input until you can get the program to work WITHOUT user input.
  4. If you posted what you intended to do with the file, you would get better answers. The most common thing to do with a file is to read it line by line, but since you are reading an html file, maybe you intend to use HTML::Parser to find certain tags, and therefore you need the whole file in one string--but then HTML::Parser can be given a file name as an argument, so you wouldn't need to read the file by hand.

Read a file line by line:

use strict; use warnings; use 5.016; my $fname = 'data.txt'; open my $INFILE, '<', $fname or die "Couldn't open $fname: $!"; while (my $line = <$INFILE>) { chomp $line; #do something to $line; } close $INFILE or die "Couldn't close $fname: $!";

Read the whole file into an array:

use strict; use warnings; use 5.016; my $fname = 'data.txt'; open my $INFILE, '<', $fname or die "Couldn't open $fname: $!"; chomp(my @lines = <$INFILE>); close $INFILE or die "Couldn't close $fname: $!";

Read the whole file into a string:

use strict; use warnings; use 5.016; my $fname = 'data.txt'; open my $INFILE, '<', $fname or die "Couldn't open $fname: $!"; my $file; { local $/ = undef; #No line terminator, so a line #is everyting in the file $file = <$INFILE>; #Read one line. } # $/ is restored to its default value of "\n" here close $INFILE or die "Couldn't close $fname: $!";