View Category
Read the contents of a file into a string
perl
@file = read()
open(my $fh, '<', $path) or die "can't open $path: $!";
$string = do { local $/; <$fh> };
close $fh;
$string = do { local $/; <$fh> };
close $fh;
Process a file one line at a time
Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
1> First line of file
2> Second line of file
3> Third line of file
perl
open(my $fh, '<', $path) or die "can't open $path: $!";
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
open my $fh, '<', $path or die "Can't open $path: $!";
while (<$fh>) {
print "$.> $_";
}
while (<$fh>) {
print "$.> $_";
}
Write a string to a file
perl
open(my $fh, '>', $path) or die "can't open $path: $!";
print $fh "This line overwites file contents!";
close $fh;
print $fh "This line overwites file contents!";
close $fh;
Append to a file
perl
open(my $fh, '>>', $path) or die "can't open $path: $!";
print $fh "This line is appended to the file!";
close $fh;
print $fh "This line is appended to the file!";
close $fh;
Process each file in a directory
perl
use File::Glob;
for (<*>) {
process_file($_) if (-f);
}
for (<*>) {
process_file($_) if (-f);
}
Process each file in a directory recursively
perl
use File::Glob;
process_directory(".");
sub process_directory {
my $dir = shift;
for my $file (<$dir/*>) {
next unless (-r $file);
if (-f $file) {
process_file($file);
} elsif (-d $file) {
process_directory($file);
}
}
}
process_directory(".");
sub process_directory {
my $dir = shift;
for my $file (<$dir/*>) {
next unless (-r $file);
if (-f $file) {
process_file($file);
} elsif (-d $file) {
process_directory($file);
}
}
}
use File::Find ();
# Traverse desired filesystems
sub process_directory {
my $directory = shift;
File::Find::find({wanted => \&wanted}, $directory);
}
sub wanted {
process_file( $File::Find::name );
}
# Traverse desired filesystems
sub process_directory {
my $directory = shift;
File::Find::find({wanted => \&wanted}, $directory);
}
sub wanted {
process_file( $File::Find::name );
}
