rkg has asked for the wisdom of the Perl Monks concerning the following question:

Hi -- I'm looking for a routine to encapsulate slurp. If no filename is given, I'd like to slurp STDIN. The code below doesn't work in this case; can someone point out why? Thanks! rkg
use strict; use FileHandle; sub slurp { my $fh = new FileHandle; my $file = 'STDIN'; $file = $_[0] if $_[0]; $fh->open($file) or die "Can't open $file: $!"; $fh->input_record_separator(undef); my $slurp = <$fh>; $fh->close or die "Can't close $file: $!"; $slurp; } print slurp();

Replies are listed 'Best First'.
Re: STDIN question
by castaway (Parson) on Jun 19, 2003 at 14:13 UTC
    There are modules which do this: File::Slurp for example..

    C.

      And how do I reference STDIN for File::Slurp? Sorry to be slow on this...rkg

        ++hmerrill

        # test2.pl use File::Slurp; $all_of_it = read_file('-'); print $all_of_it; __END__ $ >echo -e "klöhlkhklhj\nlkjhlkhlkhkk\nlkjhklhlkhklh" | perl test2.pl klöhlkhklhj lkjhlkhlkhkk lkjhklhlkhklh

        regards,
        tomte


        Hlade's Law:

        If you have a difficult task, give it to a lazy person --
        they will find an easier way to do it.

Re: STDIN question
by hmerrill (Friar) on Jun 19, 2003 at 14:19 UTC
    I'm taking a wild shot-in-the-dark here, but according to 'perldoc -f open':
    open FILEHANDLE,EXPR open FILEHANDLE,MODE,EXPR open FILEHANDLE,MODE,EXPR,LIST open FILEHANDLE,MODE,REFERENCE open FILEHANDLE <snip> In the 2-arguments (and 1-argument) form opening ’-’ opens STDIN and opening ’>-’ opens STDOUT.
    So, I'm wondering if changing your
    my $file = 'STDIN'; to my $file = '-';
    would work???

    HTH.
Re: STDIN question
by ant9000 (Monk) on Jun 19, 2003 at 15:19 UTC
    You can use typeglobs:
    use strict; print myslurp(); sub myslurp { if(shift){ open(F,"<$_") or die "Can't open $_: $!"; }else{ F=*STDIN{IO}; } local $/=undef; my $slurp=<F>; close(F); $slurp; }
Re: STDIN question
by mod_alex (Beadle) on Jun 19, 2003 at 15:43 UTC
    Hello First, please, read about file handling in perl and
    think after what $file='STDIN' means.
    check this version of your method
    #! /usr/bin/perl use strict; use warnings; use strict; use FileHandle; sub slurp { my $fh = new FileHandle; my $file = shift; local undef($/); if (defined($file)) { $fh->open($file) or die "Can't open $file: $!"; } else { $fh->fdopen(*STDIN, 'r'); } my $slurp = <$fh>; $fh->close or die "Can't close $file: $!"; $slurp; } print slurp();
    Alex