Perl Language(V) File Handler
Perl Language(V) File Handler10. Handler with the File
10.2 Sign of the IO
STDIN
standard input
my $input = <STDIN>;
print $input;
STDOUT
standard output
my $output = "Standard Output";
print "$output\n";
print STDOUT "$output\n";
STDERR
my $output = "error message";
print STDERR "$output\n";
ARGV
#!/usr/bin/perl
my $input = <ARGV>;
print "$input\n";
>perl demo3.pl demo1.pl
console output: content of demo1.pl file
my $input = shift @ARGV;
print "$input\n";
>perl demo3.pl demo1.pl
console output: demo1.pl
10.3 Basic operation of File
10.3.1 Open/Close File
open file
open FILE , "file.txt";
open OUTPUT , "<output.txt";
open INPUT , ">input.txt";
open APEND, ">>apend.txt";
close file command
close FILE;
read file command
open FILE, "<output.txt";
while (<FILE>) {
print $_;
}
open File, "foo.txt" or die "open file error: $!";
console output:
open file error: No such file or directory at /home/luohua/work/easyperl/src/demo3.pl line 3.
open FILE, "<foo.txt" or warn "open failed: $!";
while (<FILE>) {
print $_;
}
print "function end here\n";
console output:
function end here
open failed: No such file or directory at /home/luohua/work/easyperl/src/demo3.pl line 3.
10.3.3 read / write content to the file
open LOG, "output.txt" or warn "No such file: $!";
while (<LOG>) {
print $_ if (/love/);
}
output.txt:
1 sillycat
2 carl
3 hua.luo
4 love some one
5 love game
6 love basketball
console output:
4 love some one
5 love game
6 love basketball
open LOG, ">>file.txt" or warn $!;
print LOG "write to log\n" or die $!;
11. File System
11.1 More Test on file operations
my $logfile = "/var/log/messages";
if (-e $logfile) { # check if the file exist
open LOG, $logfile or die "$!";# open file
my $line_num = 1;
while (<LOG>) {
print "$line_num\t$_\n";
$line_num++;
}
} else {
print "The file not exists!\n";
}
11.2 system command function
chdir "tmp" or die $!;# "/tmp"
open LOG, ">log.txt" or die $!;
print LOG "write to log\n" or die $!;
$mode = 0644;
chmod $mode, 'tmp/log.txt';
$mode = '0644';
chmod oct($mode), 'log.txt';
@filelist = glob "*.pl";#ls
print join ";" , @filelist
console output:
demo1.pl;demo2.pl;demo3.pl
equal to
@filelist = <*.pl>;
print join ";" , @filelist
for $file (<*.txt>) {
open FH, $file;
print $file . "\n";
print $_ while (<FH>);
}
console output:
apend.txt
file.txt
write to log
write to log
input.txt
output.txt
1 sillycat
2 carl
3 hua.luo
4 love some one
5 love game
6 love basketball
syntax: mkdir PATH, umask;
mkdir foo, 0777;
syntax: rename $oldfile, $newfile;
my $file = "messages.log";
if (-e $file) {
rename $file, "$file.old";
}
open FH,">$file";
print FH "message";
#rmdir FILENAME;
rmdir foo;
my @files = <*.txt>;
unlink @files or die $!;
references:
http://easun.org/perl/perl-toc/
http://perl.apache.org/
页:
[1]