Perl 中的 open函数

首页 / Perl入门教程 / Perl 中的 open函数

描述

This function opens a file using the specified file handle. The file handle may be an expression, the resulting value is used as the handle. If no filename is specified a variable with the same name as the file handle used (this should be a scalar variable with a string value referring to the file name). The special file name '-' refers to STDIN and '>-' refers to STDOUT.

语法

以下是此函数的简单语法-

open FILEHANDLE, EXPR, LIST

open FILEHANDLE, EXPR

open FILEHANDLE

返回值

该函数在失败时返回o,在成功时返回1。

Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode.

open(DATA, "<file.txt");

DATA是将用于读取文件的文件句柄。这是打开文件并在屏幕上打印其内容的示例。

#!/usr/bin/perl

open(DATA, "<file.txt");

while(<DATA>) {
   print "$_";
}

Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in writing mode −

open(DATA, ">file.txt");

This example actually truncates (empties) the file before opening it for writing, which may not be the desired effect. If you want to open a file for reading and writing, you can put a plus sign before the > or < characters.

例如,打开文件进行更新而不截断-

open(DATA, "+<file.txt");

首先截断文件-

open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";

您可以在追加模式下打开文件。在这种模式下,写入点将设置在文件末尾。

open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";

A double >> opens the file for appending, placing the file pointer at the end, so that you can immediately start appending information. However, you can.t read from it unless you also place a plus sign in front of it −

open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";

下表列出了不同模式的可能值。

Entities    Definition
< or r		Read Only Access
> or w		Creates, Writes, and Truncates
>> or a         Writes, Appends, and Creates
+< or r+	     Reads and Writes
+> or w+	     Reads, Writes, Creates, and Truncates
+>> or a+    Reads, Writes, Appends, and Creates

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

职场求生攻略 -〔臧萌〕

如何看懂一幅画 -〔罗桂霞〕

说透芯片 -〔邵巍〕

手把手带你写一个Web框架 -〔叶剑峰〕

超级访谈:对话张雪峰 -〔张雪峰〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

中间件核心技术与实战 -〔丁威〕

结构写作力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)