How to convert from a filehandle to a string?

Discussion in 'Perl Misc' started by Bryan, Sep 5, 2007.

  1. Bryan

    Bryan Guest

    Hi,

    I have a filehandle, $file.

    I can do something like this:
    while (<$file>) {
    print $_;
    # or
    $string .= $_;
    }

    But is there a way to stuff the whole file to a string in one shot? I
    tried:
    $string = <$file>;

    But no dice.

    Thanks,
    B
     
    Bryan, Sep 5, 2007
    #1
    1. Advertising

  2. On Wed, 05 Sep 2007 15:12:37 -0700, Bryan <> wrote:

    >Subject: How to convert from a filehandle to a string?


    This doesn't make sense.

    >I have a filehandle, $file.
    >
    >I can do something like this:
    >while (<$file>) {
    > print $_;
    > # or
    > $string .= $_;
    >}
    >
    >But is there a way to stuff the whole file to a string in one shot? I
    >tried:
    >$string = <$file>;


    Read about $/ in

    perldoc perlvar

    or resort to Uri's File::Slurp.


    Michele
    --
    {$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
    (($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
    ..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
    256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
     
    Michele Dondi, Sep 5, 2007
    #2
    1. Advertising

  3. Bryan

    Guest

    On Sep 5, 6:12 pm, Bryan <> wrote:
    > Hi,
    >
    > I have a filehandle, $file.
    >
    > I can do something like this:
    > while (<$file>) {
    > print $_;
    > # or
    > $string .= $_;
    >
    > }
    >
    > But is there a way to stuff the whole file to a string in one shot? I
    > tried:
    > $string = <$file>;
    >
    > But no dice.
    >
    > Thanks,
    > B


    In addition to the info you'll find in perlvar, you can also read
    about what you want to do in:
    http://perldoc.perl.org/perlfaq5.ht...entire-file-all-at-once?-slurp-file,-slurping

    Chris
     
    , Sep 6, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Eduard W. Lohmann
    Replies:
    1
    Views:
    638
  2. Bill

    key as filehandle error

    Bill, Sep 1, 2004, in forum: Perl
    Replies:
    2
    Views:
    531
  3. Christopher Reeve
    Replies:
    1
    Views:
    466
    Kevin Goodsell
    Sep 14, 2003
  4. PerlFAQ Server
    Replies:
    0
    Views:
    112
    PerlFAQ Server
    Jan 13, 2011
  5. PerlFAQ Server

    FAQ 5.13 How can I open a filehandle to a string?

    PerlFAQ Server, Apr 7, 2011, in forum: Perl Misc
    Replies:
    0
    Views:
    129
    PerlFAQ Server
    Apr 7, 2011
Loading...

Share This Page