Perl's operations on files are similar to those of other languages, nothing more than open, read, and write operations.
1. Open the file
#! C:/perl/bin/perl-w use
UTF8;
Use strict;
Use warnings;
My $filename = ' test.txt '; # or with an absolute path, such as: C:/perl/learn/test.txt
if (open (MYFILE, $filename)) # MYFILE is a flag
{
printf "Can Open this file: %s! ", $filename;
Close (MYFILE);
}
else{
print "Can ' t open this file!";
2. Read the file
#! C:/perl/bin/perl-w use
UTF8;
Use strict;
Use warnings;
My $filename = ' test.txt ';
if (open (MYFILE, $filename))
{my
@myfile = <MYFILE>; #如果要读取多行, in this way, if you read only one behavior: $myfile = <>;
my $count = 0; #要读取的行数, the initial value is 0
printf "I have opened this file:%s\n", $filename;
while ($count < @myfile) {#遍历
print ("$myfile [$count]\n"); #注意此种写法.
$count + +;
}
Close (MYFILE);
}
else{
print "I can ' t open this file!";
}
Exit
3. Write to File
#! C:/perl/bin/perl-w use
UTF8;
Use strict;
Use warnings;
My $filename = ' test.txt ';
if (open (MYFILE, >>. $filename)) #此种写发, add not delete
{ #此种写法, rewrite file contents MYFILE, ">". $filename
Print MYFILE "Write File appending test\n";
Close (MYFILE);
}
else{
print "I can ' t open this file!";
}