• perl 如何将文件内容读到一个标量中


    将文件读入一个列表中很简单,如下:

    1 open(IN, $file); 
    2 @file = <IN>;

    但如何将文件读入到一个标量中?

    最简单的方法是设置perl内置变量$/,如下:

    1 #!/usr/bin/perl -w
    2 use strict;
    3 open my $fh, '<', 'file.txt' or die $!; #系统或库调用fail时会设置$!
    4 my $content = do { local $/; <$fh> };

    或者也可以用undef:

    1 my $file = "file.txt";
    2 open (IN, "<$file") || die "Cannot open file: $file";
    3 undef $/; #local $/;
    4 my $content = <IN>;
    5 close IN;

    这里关键是变量$/. 

    $/的值默认是换行符,因此一般情况下我们使用<>读取文件时都是一行一行读取的,使用local或者undef将使得读取文件直到文件结尾。如下:

    1 local $/; # enable "slurp" mode
    2 local $_ = <FH>; # whole file now here

    一个完整应用的例子:

    1 my $content; 
    2 if ( open my $fh, '<', 'file.txt' ) {
    3 $content = do { local $/; <$fh> };
    4 close $fh;
    5 } else {
    6 $content = 'The file could not be opened.';
    7 }

    ========================================

    关于$/还有一点值得补充:
    设置 $/ 为一个整数的引用,包含整数的标量,或者可以转换为整数的标量(reference to an integer, scalar containing an integer, or scalar that's convertible to an integer),将会从文件中读取不超过该整数字节的数据,比如:

    1 local $/ = \32768; # or \"32768", or \$var_containing_32768
    2 open my $fh, "<", $myfile or die $!;
    3 local $_ = <$fh>;

    将从文件读取不超过 32768 bytes的数据。

    另外需要注意的是$/的值是一个字符串,不是一个正则表达式。
    关于$\以及其他变量,可参考perldoc perlvar

    ========================================
    其他的方法还有:
    1.使用join函数

    1 open(IN, $file) or die $!; 
    2 my $content = join("", <IN>);
    3 close IN;

    2.使用列表转换成标量

    一个完整的用法的例子:

     1 my $content; 
    2 my $opened = open(IN, $file);
    3 if (!$opened) {
    4 $content = "Error.";
    5 } else {
    6 @lines = <IN>;
    7 foreach $LINE (@lines) {
    8 $content .= $LINE;
    9 }
    10 close(IN);
    11 }
  • 相关阅读:
    洛谷P1002 过河卒
    XAF 接口和BOModel<DC翻译博客四>
    XAF DC中的关联<DC翻译博客三>
    XAF 组合关联<DC翻译博客十一>
    XAF 转换不同应用程序模型
    XAF How to: Implement Domain Components(如何实现领域构件)
    XAF 对基库的思考<DC翻译博客五>
    XAF–The State of Domain Components Technology in V2010 Vol 2
    Xpand Easy Sequential numbers(易用的序列号)
    XAF 如何实现批量更改多列多行单元格的值
  • 原文地址:https://www.cnblogs.com/yuyan/p/2300284.html
Copyright © 2020-2023  润新知