in reply to slurping into scalars

You are *so* close on this one - I think the following is what you are after ...

$data = do { local $/ = undef; <$file> };

What this line of code does is clear the input record separator, $/, which is a newline character by default and delimits Perl's concept of what a "line" is. By undefining this variable, the first read of this file handle, <$file>, slurps the entire file into the variable. This behaviour is documented in perlvar.

 

Update

See particle's post in this thread here for an alternate method which also harnesses the magic of @ARGV allowing for the slurping of entire files into either an array or scalar using only a single line of code - For example: [@data|$data] = do { local( $/ ) = wantarray ? $/ : undef; local( @ARGV ) = @_; <> };

 

perl -le 'print+unpack("N",pack("B32","00000000000000000000000111110111"))'

Replies are listed 'Best First'.
Re: Re: slurping into scalars
by Anonymous Monk on Dec 16, 2002 at 10:17 UTC
    Is it possible to alter this so every new-line is printed to a new-line?? for some reason this merges all lines together. ;-)
      This is not normal behaviour and where we will need to see some code to understand what is happening. Altering the value of the input record separator, $/, in the manner described has no effect on the substance of the data read into the scalar variable.

       

      perl -le 'print+unpack("N",pack("B32","00000000000000000000000111111000"))'

      Is it possible to alter this so every new-line is printed to a new-line?? for some reason this merges all lines together.
      $_ = join("\n", <FILE>);
      Adds a second \n to every line. This may be what you are looking for. Seems a bit odd though.

      I have done this kind of thing (with some differences) when doing quick and dirty text->html output. Say you want to put <p> tags when you have blank lines but otherwise leave the text untouched then the folowing code works:

      do {local $/ = $/.$/;print join('<p>', <FILE>);};

      Dingus


      Enter any 47-digit prime number to continue.