Main

March 31, 2004 (Wednesday)

File Handles (S&P — Chapter 11)

Like C's fopen() and fclose() function, Perl supports a means of doing input and output to a file. To demonstrate File I/O in Perl, consider the following script:

#!/usr/bin/perl -w

use strict;

my ($passwd, $results) = qw< /etc/passwd results.out >;

my %shells;
open FILE, $passwd or die "Cannot open password file: $!\n";
while (<FILE>) {
	chomp;
	next if /ppp/;
	$shells{(split /:/)[-1]} ++;
}
close FILE or die "Cannot close password file: $!\n";

open RES, "> $results" or die "Cannot open '$results' for write: $!\n";
for (sort { $shells{$b} <=> $shells{$a} } keys %shells ) {
	print RES "$_: $shells{$_}\n";
}
close RES or die "Cannot close $results'";
fio.pl

There are several things to note about the above script:


Last modified: March 29, 2004 17:36:39 NST (Monday)