הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Working With Files

Working with files in perl is just a general case of working with standard input and output.

Here are some examples:

use strict;
use warnings;

####### 
# cat.pl takes a file name as argument and prints its content on screen
#

my $src = shift or die "cat.pl takes a file name as argument";
 
open my $src_h, "<", $src  or die "Failed to open file $src - $!\n";
 
while(<$src_h>) {
  print;
}
 
close $src_h ;
use strict;
use warnings;

#############
# copy.pl takes two file names as arguments, and copies the first file's content
# into the second
#
 
my $source = shift or die "copy.pl expects two arguments";
my $dest = shift or die "copy.pl expects two arguments";
 
open my $src_h, "<", $source  or die "failed to open file $source - $!\n";
open  my $dst_h, ">", $dest  or die "Failed to open file $dest - $!\n";
 
print $dst_h $_ while(<$src_h>);
 
close($src_h);
close($dst_h);
use strict;
use warnings;
##################
# Reads a file and change every 'cat' to 'dog' by using
# a temporary file
#
# Note: this program does not work well if the .tmp file already exists
#
 
my $filename = shift or die "Usage: change.pl <filename>";
 
open my $fin, '<', $filename or die $!;
open my $fout, '>', "$filename.tmp" or die $!;
 
while (my $line = <$fin>) {
    $line =~ s/cat/dog/g;
    print $fout $line;
}
 
close $fin;
close $fout;
 
rename "$filename.tmp", $filename;
course: