my $handle = undef; # this will be filled in on success
open($handle, "< $encoding", $filename)
- || die "$0: can't open $filename for reading: $!\n";
+ || die "$0: can't open $filename for reading: $!";
As with the shell, in Perl the C<< "<" >> is used to open the file in
read-only mode. If it succeeds, Perl allocates a brand new filehandle for
open mode:
open($handle, "<", $filename)
- || die "$0: can't open $filename for reading: $!\n";
+ || die "$0: can't open $filename for reading: $!";
But never use the bare C<< "<" >> without having set up a default encoding
first. Otherwise, Perl cannot know which of the many, many, many possible
my $encoding = ":encoding(UTF-8)";
open($handle, ">> $encoding", $filename)
- || die "$0: can't open $filename for appending: $!\n";
+ || die "$0: can't open $filename for appending: $!";
Now you can write to that filehandle using any of C<print>, C<printf>,
C<say>, C<write>, or C<syswrite>.
my $encoding = ":encoding(UTF-8)";
open($handle, "> $encoding", $filename)
- || die "$0: can't open $filename in write-open mode: $!\n";
+ || die "$0: can't open $filename in write-open mode: $!";
Here again Perl works just like the shell in that the C<< ">" >> clobbers
an existing file.
C<<< ">" >>> as needed:
open($handle, "< $encoding", $filename)
- || die "$0: can't open $filename for reading: $!\n";
+ || die "$0: can't open $filename for reading: $!";
open($handle, ">> $encoding", $filename)
- || die "$0: can't open $filename for appending: $!\n";
+ || die "$0: can't open $filename for appending: $!";
open($handle, "> $encoding", $filename)
- || die "$0: can't open $filename in write-open mode: $!\n";
+ || die "$0: can't open $filename in write-open mode: $!";
Alternately, you can change to binary mode on an existing handle this way:
You can also pass C<binmode> an explicit encoding to change it on the fly.
This isn't exactly "binary" mode, but we still use C<binmode> to do it:
- binmode(STDIN, ":encoding(MacRoman)") || die "cannot binmode STDIN";
- binmode(STDOUT, ":encoding(UTF-8)") || die "cannot binmode STDOUT";
+ binmode(STDIN, ":encoding(MacRoman)") || die "cannot binmode STDIN";
+ binmode(STDOUT, ":encoding(UTF-8)") || die "cannot binmode STDOUT";
Once you have your binary file properly opened in the right mode, you can
use all the same Perl I/O functions as you used on text files. However,
my($in_fh, $out_fh, $buffer);
- open($in_fh, "<", $name_in) || die "$0: cannot open $name_in for reading: $!";
- open($out_fh, ">", $name_out) || die "$0: cannot open $name_out for writing: $!";
+ open($in_fh, "<", $name_in)
+ || die "$0: cannot open $name_in for reading: $!";
+ open($out_fh, ">", $name_out)
+ || die "$0: cannot open $name_out for writing: $!";
for my $fh ($in_fh, $out_fh) {
binmode($fh) || die "binmode failed";