Tuesday, December 9, 2008

perl: manipulations with standart output stream

Builtin functions print and write put data to stdout if the filehandle is omitted.
This is really handy.
But since you want to write to some other stream each time you have to specify filehandle for them.
It's possible to point STDOUT to some other filehandle by reassigning it

open $nfh, '>test';
$ofh = *STDOUT;
*STDOUT = *$nfh;

print "test";

*STDOUT = $ofh;
close $nfh;
or by using select function
open $nfh, '>test';
$ofh = select $nfh;

print "test";

select $ofh;
close $nfh;
and still use print and write w/o specifying the filehandle. The second method with select looks better for me.
If you use a lot of ways for output the LIFO(Last-In, First-Out) of filehandles can be used to implement an easy way to walk through them like pushd/popd in bash
#!/usr/bin/perl
@fh = ();

open my $nfh, '>test-0';
push @fh, select $nfh;

print "test\n";

open my $nfh, '>test-1';
push @fh, select $nfh;

print "test\n";

close select pop @fh;
print "test\n";
close select pop @fh;

print "test\n";
The result of executing this script
$./test.pl 
test
$cat test-*
test
test
test
Note, I used my with filehandle in open to give it an undefined scalar variable. Otherwise open will associate the stream with this variable. And the old stream will be lost. The following code does the same work w/o using my expression
#!/usr/bin/perl
@fh = ();

open $nfh, '>test-0';
push @fh, select $nfh;

print "test\n";

$nfh = undef;
open $nfh, '>test-1';
push @fh, select $nfh;

print "test\n";

close select pop @fh;
print "test\n";
close select pop @fh;

print "test\n";
The result of executing this script
$./test.pl 
test
$cat test-*
test
test
test

2 comments:

Demon said...

Perl is the best scripting language for Text processing and handle regex. I have posted few articles related to those at my blog

http://icfun.blogspot.com/search/label/perl

Also Perl's Cpan has lots of support that I don't even need to think extra while developing project. I didn't find such help on other programming language except Java and .NET

Ni@m said...

I agree, PERL is awesome for text processing. CPAN is great also but too often you can find few modules there that might fit your purpose and you stand in front of problem of choice. I think it's too big and now it have to be cleaned up.