File operation of Perl learning notes

Time:2021-11-24

Perl’s operation on files is similar to other languages, that is, the operation of opening, reading and writing.
1. Open the file

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#! c:/perl/bin/perl -w
use utf8;
use strict;
use warnings;
 
my $filename = 'test.txt'; #Or use 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 file

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#! c:/perl/bin/perl -w
use utf8;
use strict;
use warnings;
 
my $filename = 'test.txt'
if(open(MYFILE,$filename))
{
 my @myfile = <MYFILE>;  #If you want to read multiple lines, use this method. If you only read one line: $myfile = < >;
 my $count = 0;     #The number of rows to read. The initial value is 0
 printf "I have opened this file: %s\n", $filename;
 while($count < @myfile){ #Traversal
  print ("$myfile[$count]\n"); #Pay attention to this way of writing
  $count++;
 }
 close(MYFILE);
}
else{
 print "I can't open this file!";
}
exit;

3. Write file

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#! c:/perl/bin/perl -w
use utf8;
use strict;
use warnings;
 
my $filename = 'test.txt'
 
if(open(MYFILE,">>".$filename))  #This kind of writing and sending cannot be added or deleted
{                 #In this way, rewrite the file content myfile, ">". $filename
 print MYFILE "Write File appending Test\n";
 close(MYFILE);
}
else{
 print "I can't open this file!";
}
exit;

 

Recommended Today

Seven solutions for distributed transactions

1、 What is distributed transaction Distributed transaction means that transaction participants, transaction supporting servers, resource servers and transaction managers are located on different nodes of different distributed systems. A large operation is completed by more than n small operations. These small operations are distributed on different services. For these operations, either all of them are […]