- $
Opening a file - error handling
- $! - error message from the Operating system
examples/files-perl/open_with_if.pl
#!/usr/bin/perl use strict; use warnings; my $filename = "input.txt"; if (open my $in, "<", $filename) { # do your thing here # no need to explicitly close the file } else { warn "Could not open file '$filename'. $!"; } # here the $in filehandle is not accessible anymore
A more Perlish way to open a file and exit with error message if you could not open the file:
examples/files-perl/open_with_die.pl
#!/usr/bin/perl use strict; use warnings; my $filename = "input.txt"; open(my $fh, "<", $filename) or die "Could not open file '$filename'. $!"; # do your thing here close $fh;