如何在Perl中将小文本文件的内容读入标量? [英] How do I read the contents of a small text file into a scalar in Perl?

查看:184
本文介绍了如何在Perl中将小文本文件的内容读入标量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的文本文件,我想读入一个标量变量,就像它在文件中一样(保留行分隔符和其他空格)。

Python中的等价物就像

  buffer =

try:
file = open(fileName,'rU')
try:
buffer + = file.read()
finally:
file.close()
除了IOError:
buffer + =文件无法打开。

这是为了简单地重新显示网页上的文件内容,这就是为什么我的错误信息正在进入我的文件缓冲区。 解决方案

Perl Cookbook

  my $ filename ='file 。文本'; 
打开(FILE,'<',$ filename)或死掉'Could not open file:'。 $ !;

undef $ /;
my $ whole_file =< FILE> ;;

我会将这些更改本地化:

  my $ whole_file =''; 
{
local $ /;
$ whole_file =< FILE>;
}


I have a small text file that I'd like to read into a scalar variable exactly as it is in the file (preserving line separators and other whitespace).

The equivalent in Python would be something like

buffer = ""

try:
    file = open("fileName", 'rU')
    try:
        buffer += file.read()
    finally:
        file.close()
except IOError:
    buffer += "The file could not be opened."

This is for simply redisplaying the contents of the file on a web page, which is why my error message is going into my file buffer.

解决方案

From the Perl Cookbook:

my $filename = 'file.txt';
open( FILE, '<', $filename ) or die 'Could not open file:  ' . $!;

undef $/;
my $whole_file = <FILE>;

I would localize the changes though:

my $whole_file = '';
{
    local $/;
    $whole_file = <FILE>;
}

这篇关于如何在Perl中将小文本文件的内容读入标量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆