Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read from a method that returns a filehandle in Perl?

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>;
like image 637
Ryan C. Thompson Avatar asked Nov 23 '25 14:11

Ryan C. Thompson


2 Answers

You could consider spelling <...> as readline(...) 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.

like image 161
hobbs Avatar answered Nov 26 '25 16:11

hobbs


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.

like image 37
DougWebb Avatar answered Nov 26 '25 16:11

DougWebb