Perl Basics
Introduction to Perl
FAQ's
CGI
Regular Expressions

PC Overview
Cool Stuff
My Modules
Success Stories
Links
Perl in the News
Logos

PC Internals
About
Contact
Handy Logos
What's new

Re-open the STDIN file handle

How to rewind the STDIN file handle?
P-friendly

[ home ] - [ search ] - [ sitemap ]


In special cases it can be needed to re-read from the STDIN file handle, e.g. in a mail or Listserver processing with Perl. There might be even more sophisticated solutions on this problem but the following one will work. If you had a better recipe please let me know.

How to test this example:

ls -l /tmp | script.pl

Recipe

#!/usr/bin/perl -w
use strict;
$| = 1;

local *FH;

*FH = &stdin(); # Now you have a rewind-able file handle to your STDIN data

# -- first run
while(<FH>) {
        print "[R1]=> $_";
}

seek(FH, 0, 0);

# -- second run
while(<FH>) {
        print "[R2]=> $_";
}

sub stdin () {
        my $tempfile = time() . '_' . int(rand(1000000));
        open(TEMP, "+>/tmp/temp_$tempfile") or print STDERR $!;
        local $/ = undef;
        print TEMP <STDIN>;
        seek(TEMP, 0, 0);
        \*TEMP;
}
home - feedback - search

$Id: foo.htm,v 1.10 2004/03/11 17:50:01 reto Exp $
© 1998-2004 reto :)