# Basic syntax:
# For reading:
open(my $in, "<", "infile.txt") or die "Can't open infile.txt: $!";
# For writing (overwrites file if it exists):
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
# For writing (appends to end of file if it exists):
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Where:
# The first argument to open creates a named filehandle that can be
# referred to later
# The second argument determines how the file will be opened
# The third argument is the file name (use $ARGV[#] if reading from the CLI)
# The or die "" portion is what to print if there is an error opening the file
# Note, be sure to close the filehandle after you're done operating on the file:
close $in;
# You can read from an open filehandle using the "<>" operator. In
# scalar context it reads a single line from the filehandle, and in list
# context it reads the whole file in, assigning each line to an element
# of the list:
my $line = <$in>;
my @lines = <$in>;
# You can iterate through the lines in a file one at a time with a while loop:
while (my $line = <$in>) {
print "Found apples
" if $line =~ m/apples/;
}
# You can write to an open filehandle using the standard "print" function:
print $out @lines;
print $log $msg, "
";
#!/usr/bin/perl
use warnings;
use strict;
my $filename = 'c: emp est.txt';
open(FH, '<', $filename) or die $!;
while(<FH>){
print $_;
}
close(FH);
Code language: Perl (perl)