📜  珀尔 |写入文件

📅  最后修改于: 2022-05-13 01:55:18.158000             🧑  作者: Mango

珀尔 |写入文件

文件句柄是用于读取和写入文件的变量。此文件句柄与文件相关联。

为了写入文件,它以写入模式打开,如下所示:

open (FH, ‘>’, “filename.txt”);

如果文件存在,那么它将用新内容截断文件的旧内容。否则将创建一个新文件并添加内容。

打印()函数

print()函数用于将内容写入文件。

在这里,文件句柄在打开文件时与文件相关联,字符串保存要写入文件的内容。

例子 :

# Opening file Hello.txt in write mode
open (fh, ">", "Hello.txt");
  
# Getting the string to be written
# to the file from the user
print "Enter the content to be added\n";
$a = <>;
  
# Writing to the file
print fh $a;
  
# Closing the file
close(fh) or "Couldn't close the file"; 

写入文件之前:

执行代码写入:

更新后的文件:

以下是该程序的工作原理:
第 1 步:以写入模式打开文件 Hello.txt。
第 2 步:从标准输入键盘获取文本。
步骤 3:将存储在 '$a' 中的字符串写入文件句柄 'fh' 指向的文件
第四步:关闭文件。将内容从一个文件复制到另一个文件:

代码执行前:
源文件:

目标文件:

例子 :
下面的示例从源文件中读取内容并将其写入目标文件。

# Source File 
$src = 'Source.txt';
  
# Destination File
$des = 'Destination.txt';
  
# open source file for reading
open(FHR, '<', $src);
   
# open destination file for writing
open(FHW, '>', $des); 
   
print("Copying content from $src to $des\n");
while()
{
   print FHW $_; 
}
   
# Closing the filehandles
close(FHR);
close(FHW);
   
print "File content copied successfully!\n";

执行代码:

更新的目标文件:

以下是该程序的工作原理:-
第 1 步:在读取模式下打开 2 个文件 Source.txt,在写入模式下打开 Destination.txt。
第 2 步:从 FHR 中读取内容,这是读取内容的文件句柄,而 FHW 是用于将内容写入文件的文件句柄。
第三步:使用打印函数复制内容。
第 4 步:读取文件完成后关闭 conn。

错误处理和错误报告

有两种方法可以处理错误

  • 如果文件无法打开,则抛出异常(处理错误)
  • 如果文件无法打开并继续运行,则发出警告(错误报告)

抛出异常(使用 Die函数)
当当时无法为文件句柄分配有效的文件指针时,将执行 die 打印消息并终止当前程序。
例子 :

# Initializing filename  
$filename = 'Hello.txt'; 
# $filename = 'ello.txt';
  
# Prints an error and exits 
# if file not found 
open(fh, '<', $filename) or 
     die "Couldn't Open file $filename"; 

在上面的代码中,当文件存在时,它只是简单地执行而没有错误,但如果文件不存在,那么它会生成一个错误并且代码终止。

发出警告(使用警告函数)
当文件句柄无法分配有效的文件指针时,它只会使用警告函数打印警告消息并继续运行。
例子 :

# Initializing filename 
$filename = 'GFG.txt'; 
  
# Opening a file and reading content 
if(open(fh, '<', $filename)) 
{ 
    while() 
    { 
        print $_; 
    } 
} 
  
# Executes if file not found 
else
{ 
  warn "Couldn't Open a file $filename"; 
} 

当文件存在时:

当文件不存在时: