Perl:避免从标准输入中贪婪地阅读? [英] Perl: avoid greedy reading from stdin?

查看:25
本文介绍了Perl:避免从标准输入中贪婪地阅读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 perl 脚本 (read.pl):

Consider the following perl script (read.pl):

my $line = <STDIN>;
print "Perl read: $line";
print "And here's what cat gets: ", `cat -`;

如果这个脚本是从命令行执行的,它会得到第一行输入,而cat得到其他一切,直到输入结束(^D是按下).

If this script is executed from the command line, it will get the first line of input, while cat gets everything else until the end of input (^D is pressed).

但是,当输入是从另一个进程通过管道传输或从文件中读取时,情况就不同了:

However, things are different when the input is piped from another process or read from a file:

$ echo "foo\nbar" | ./read.pl
Perl read: foo
And here's what cat gets:

Perl 似乎在某处大量缓冲整个输入,而使用反引号或系统调用的进程看不到任何输入.

Perl seems to greadily buffer the entire input somewhere, and processes called using backticks or system do no see any of the input.

问题是我想对混合了 <STDIN> 和调用其他进程的脚本进行单元测试.什么是最好的方法来做到这一点?我可以在 perl 中关闭输入缓冲吗?或者我可以以模仿"终端的方式来缓冲数据吗?

The problem is that I'd like to unit test a script that mixes <STDIN> and calls to other processes. What would be the best way to do this? Can I turn off input buffering in perl? Or can I spool the data in a way that will "mimic" a terminal?

推荐答案

今天我想我找到了我需要的东西:Perl 有一个名为 Expect 非常适合这种情况:

Today I think I've found what I needed: Perl has a module called Expect which is perfect for such situations:

#!/usr/bin/perl

use strict;
use warnings;

use Expect;

my $exp = Expect->spawn('./read.pl');
$exp->send("First Line\n");
$exp->send("Second Line\n");
$exp->send("Third Line\n");
$exp->soft_close();

就像一个魅力;)

这篇关于Perl:避免从标准输入中贪婪地阅读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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