如何伪造输入到perl的钻石操作员? [英] How to fake input to perl's diamond operator?
问题描述
此问题的答案描述了如何伪输入< STDIN>
。我的目标类似于这个问题:我的单元测试需要假输入<>
。
The answers to this question describe how to fake input to <STDIN>
. My goal is similar to that question: my unit test needs to fake input to <>
.
我使用相同的技术假冒<>
的输入,它不起作用。 <>
的介绍级解释让我相信,当命令行上没有给出文件时,它正在从STDIN读取,但这似乎没有是这样的。
When I apply the same technique to fake input to <>
, it doesn't work. The introductory-level explanations of <>
led me to believe that it was reading from STDIN when no files are given on the command line, but this doesn't seem to be the case.
我正在努力工作的样本:
The sample I'm trying to make work:
#!/usr/bin/perl -w
use strict;
use warnings;
use Carp;
use English qw( -no_match_vars );
sub fake1 {
my $fakeinput = "asdf\n";
open my $stdin, '<', \$fakeinput
or croak "Cannot open STDIN to read from string: $ERRNO";
local *STDIN = $stdin;
my $line = <>;
print "fake1 line is $line\n";
return 0;
}
sub fake2 {
my $fakeinput = "asdf\n";
open my $stdin, '<', \$fakeinput
or croak "Cannot open STDIN to read from string: $ERRNO";
local *STDIN = $stdin;
my $line = <STDIN>;
print "fake2 line is $line\n";
return 0;
}
fake1();
fake2();
fake2
有效, fake1
没有。一个示例会话(qwerty是我打字):
fake2
works, fake1
does not. A sample session (the "qwerty" is me typing):
$ perl /tmp/diamond.pl
qwerty
fake1 line is qwerty
fake2 line is asdf
我的问题:
- 如何伪造输入
<>
? -
<>
和< STDIN>
之间有什么区别?文件在命令行中给出? (即为什么链接问题中的技术适用于< STDIN>
但不适用于<>
? )
- How can I fake input to
<>
? - What's the difference between
<>
and<STDIN>
when no files are given on the command line? (I.e. Why does the technique in the linked question work for<STDIN>
but not for<>
?)
谢谢。
推荐答案
在第一次测试中试试这个:
Try this in your first test:
open ARGV, '<', \$fakeinput
or croak "Cannot open STDIN to read from string: $ERRNO";
my $line = <>;
print "fake1 line is $line\n";
这样做的缺点是不是本地 - 不知道你是否可以在本地制作。
(你可以多次这样做,在每次测试前重置。)
This has the disadvantage of not being "local" - no idea if you can make it local or not. (You can do that several times though, resetting before each test.)
这篇关于如何伪造输入到perl的钻石操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!