develooper Front page | perl.perl5.porters | Postings from February 2011

$/ = \1024 useless on non-bytes files--but needn't be

Thread Next
From:
Tom Christiansen
Date:
February 28, 2011 15:54
Subject:
$/ = \1024 useless on non-bytes files--but needn't be
Message ID:
8774.1298937288@chthon
As it has read since 5.6:

    Setting C<$/> to a reference to an integer, scalar containing an
    integer, or scalar that's convertible to an integer will attempt to
    read records instead of lines, with the maximum record size being the
    referenced integer. So this:

	local $/ = \32768; # or \"32768", or \$var_containing_32768
	open my $fh, "<", $myfile or die $!;
	local $_ = <$fh>;

    will read a record of no more than 32768 bytes from FILE. If you're
    not reading from a record-oriented file (or your OS doesn't have
    record-oriented files), then you'll likely get a full chunk of data
    with every read. If a record is larger than the record size you've
    set, you'll get the record back in pieces. Trying to set the record
    size to zero or less will cause reading in the (rest of the) whole file.

That's pretty darned useless/destructive/broken if you're reading from 
a stream that has a variable-width encoding layer slapped down it.  I 
almost think it shouldn't let you do it at all!

While this fails miserably:

    % perl -CS -le 'print 248.555.2359.2331.412.191.1310.4423.102113134.535 x 10' | perl -CS -e '$/ = \5; printf "%vd\n", $_ while <>'

This works just fine:

    % perl -CS -le 'print v248.555.2359.2331.412.191.1310.4423.102113134.535 x 10' | perl -CS -e 'while (read(STDIN, $var, 5)) { printf "%vd\n", $var }'

Why isn't the first mapping to the second instead of giving bogus
and broken results?

--tom

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About