如何从 Perl 中返回文件句柄的方法中读取内容?
我有一个对象,它的方法返回一个文件句柄,我想从该句柄中读取数据。以下内容不起作用,因为方法调用的右尖括号被解释为输入读取器的右尖括号:
my $input = <$object->get_handle()>;
被解析为:
my $input = ( < $object- > ) get_handle() >;
这显然是一个语法错误。有什么方法可以在角度运算符中执行方法调用,或者我需要将其分为这样的两个步骤吗?
my $handle = $object->get_handle();
my $input = <$handle>;
I have an object with a method that returns a filehandle, and I want to read from that handle. The following doesn't work, because the right angle bracket of the method call is interpreted as the closing angle bracket of the input reader:
my $input = <$object->get_handle()>;
That gets parsed as:
my $input = ( < $object- > ) get_handle() >;
which is obviously a syntax error. Is there any way I can perform a method call within an angle operator, or do I need to break it into two steps like this?
my $handle = $object->get_handle();
my $input = <$handle>;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以考虑将
...
>
拼写为readline(
<而是使用strong>...
)
,它通过使用良好的常规语法而不是特殊情况来避免该问题。或者您可以将其分配给标量。你的选择。You could consider spelling
<
...
>
asreadline(
...
)
instead, which avoids the problem by using a nice regular syntax instead of a special case. Or you can just assign it to a scalar. Your choice.你必须把它打破; <>运算符需要像这样的 typeglob,一个包含对文件句柄或像 <$fh> 这样的 typeglob 的引用的简单标量变量,或者像 <*.c> 这样的 glob() 函数的参数。在您的示例中,您实际上正在调用 glob('$object-')。
<>实际上被解释为对 readline() 的调用,因此如果您确实想要,您可以说
my $input = readline( $object->get_handle() );
我不确定这是否更干净不过,特别是如果您要多次读取句柄的话。请参阅 http://perldoc.perl.org/perlop.html#I%2fO - 操作员了解详细信息。
You have to break it up; the <> operator expects a typeglob like <STDIN>, a simple scalar variable containing a reference to a filehandle or typeglob like <$fh>, or an argument for the glob() function like <*.c>. In your example, you're actually calling glob('$object-').
<> is actually interpreted as a call to readline(), so if you really want to you could say
my $input = readline( $object->get_handle() );
I'm not sure that's cleaner though, especially if you're going to read from the handle more than once.See http://perldoc.perl.org/perlop.html#I%2fO-Operators for details.
或者
or
您将无法在此处使用
<...>
运算符来读取文件句柄,因为任何比
或更复杂的内容><$scalar>
被解释为glob(...)
调用,因此通常的消歧技巧在这里不起作用。
运算符是readline HANDLE
的语法糖,因此您可以这样编写:但是,如果您要在循环中执行此操作,它将是将句柄缓存在标量中会更有效。然后
<...> 运算符将按您的预期工作:
You won't be able to use the
<...>
operator here to read a file handle, because anything more complex than<bareword>
or<$scalar>
is interpreted as aglob(...)
call, so none of the usual disambiguation tricks will work here. The<HANDLE>
operator is syntactic sugar forreadline HANDLE
, so you could write it this way:However, if you will be doing this in a loop, it will be far more efficient to cache the handle in a scalar. Then the
<...>
operator will work as you expected: