Tutorial by Examples

my $filename = '/path/to/file'; open my $fh, '<', $filename or die "Failed to open file: $filename"; # You can then either read the file one line at a time... while(chomp(my $line = <$fh>)) { print $line . "\n"; } # ...or read whole file into an arra...
This code opens a file for writing. Returns an error if the file couldn't be opened. Also closes the file at the end. #!/usr/bin/perl use strict; use warnings; use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding # Open "output.txt" for writing (">") and ...
Opening Generic ASCII Text Files 5.6.0 open my $filehandle, '<', $name_of_file or die "Can't open $name_of_file, $!"; This is the basic idiom for "default" File IO and makes $filehandle a readable input stream of bytes, filtered by a default system-specific decoder, which...
Before reading and writing text files you should know what encoding to use. See the Perl Unicode Documentation for more details on encoding. Here we show the setting of UTF-8 as the default encoding and decoding for the function open. This is done by using the open pragma near the top of your code (...
autodie allows you to work with files without having to explicitly check for open/close failures. Since Perl 5.10.1, the autodie pragma has been available in core Perl. When used, Perl will automatically check for errors when opening and closing files. Here is an example in which all of the lines ...
Sometimes it is needful to backtrack after reading. # identify current position in file, in case the first line isn't a comment my $current_pos = tell; while (my $line = readline $fh) { if ($line =~ /$START_OF_COMMENT_LINE/) { push @names, get_name_from_comment($line); ...
Writing a gzipped file To write a gzipped file, use the module IO::Compress::Gzip and create a filehandle by creating a new instance of IO::Compress::Gzip for the desired output file: use strict; use warnings; use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding use IO::Compres...
# encode/decode UTF-8 for files and standard input/output use open qw( :encoding(UTF-8) :std ); This pragma changes the default mode of reading and writing text ( files, standard input, standard output, and standard error ) to UTF-8, which is typically what you want when writing new application...

Page 1 of 1