如何使用 Perl 一次阅读段落? [英] How do I read paragraphs at a time with Perl?

查看:38
本文介绍了如何使用 Perl 一次阅读段落?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写

#!/usr/bin/perl -w使用严格;而(<数据>){打印 "\n-------------------------\n\n";打印;<>;}

每次返回"后,我都会得到一行.

为什么我没有在每次返回"一个段落后得到下一个脚本?

#!/usr/bin/perl -w使用严格;本地 $/= "";而(<数据>){打印 "\n-------------------------\n\n";打印;<>;}__数据__第一行第二行第三行第四行五号线第六行第七行第八行第九行第十行十一号线第十二行

解决方案

在您的第一个脚本中,将 $/变量设置为默认值\n",一次只返回一行.

我相信第二个脚本可以满足您的要求,只是 <>不会在返回"时终止读取,而是在 时终止读取.由于您的 $/设置(正如其他人指出的 <> 从 STDIN 读取,但我认为您已经知道这一点并且正在使用它来调节输出).

如果你真的想用'return'来调节输出,那么你需要在循环中用$/做更多的事情.

<前>而(<数据>){打印 "\n-------------------------\n\n";打印;$/= "\n";# default 以便以下内容在返回"时终止读取<>;$/= "";}

When I write

#!/usr/bin/perl -w
use strict;

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    <>;
}

after each "return" I get one line.

Why don't I get with the next script after each "return" one paragraph?

#!/usr/bin/perl -w
use strict;

local $/ = "";

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    <>;
}

__DATA__
line one
line two
line three
line four
line five

line six
line seven
line eigth
line nine

line ten
line eleven
line twelve

解决方案

In your first script, with the $/ variable set to default "\n", the <DATA> will only return one line at a time.

I believe the second script does what you want, it's just that <> won't terminate the read on a 'return' but rather on a <ctrl-d> due to your $/ setting (as someone else pointed out <> reads from STDIN but I think you already know that and are using it to regulate the output).

If you really want to regulate the output with 'return' then you need to do more with $/ in the loop.

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    $/ = "\n"; # default so that the following terminates the read on 'return'
    <>;
    $/ = ""; 
}   

这篇关于如何使用 Perl 一次阅读段落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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