Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does open(STDOUT,'>:scalar', \$stdout) work in Perl?

Tags:

perl

What does >:scalar mean?

Never see this kind of code before..

like image 853
asker Avatar asked Sep 21 '11 07:09

asker


1 Answers

The particular ">:THING" syntax tells the Perl IO system to use the layer specified by THING. Have a look at the PerlIO documentation for 'layer'. Common layers are 'raw' and 'utf8'.

In this case, this allows you to use $stdout as an in-memory file which should end up containing whatever gets sent to STDOUT. More generally, the syntax lets you open an in-memory file, then send the filehandle to other functions that normally write to files, so that you can collect their output (or provide their input).

You can also achieve the same result by opening a "file" which is a reference to a scalar:

open my $fh, ">:scalar",  \$scalar or die;
open my $fh, ">",  \$scalar or die;

It's provided by PerlIO, and implemented by PerlIO::scalar, although you do not have to 'use' the module to access the functionality.

like image 69
Alex Avatar answered Oct 28 '22 13:10

Alex