in reply to Re^2: sending data thru a sub routine
in thread sending data thru a sub routine

"... binary and plain text ..."

Hmm, not really. You are dealing with a binary file that happens to have some plain text fields. unpack makes the code easier and clearer - in this case it even makes it correct. Consider:

use strict; use warnings; (my $binStr = <<BIN) =~ s/\n//g; \x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00 The end of the world is neigh \x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00 unless you use pack and unpack BIN open my $fIn, '<', \$binStr; binmode $fIn; print "Using unpack\n"; while (read($fIn, (my $rec), 48)) { my ($fileLocL, undef, $fileSizeL, undef, $fileName) = unpack('VVVVa32', $rec); printf "Loc: %d, Size: %d, Name: '%s'\n", $fileLocL, $fileSizeL, $ +fileName; } seek $fIn, 0, 0; print "Using bogus substitution code\n"; while (!eof $fIn) { my ($fileLoc, $fileSize, $fileName); read($fIn, $fileLoc, 0x08); read($fIn, $fileSize, 0x08); read($fIn, $fileName, 0x20); $fileLoc =~ s/(.)/sprintf("%02x",ord($1))/eg; $fileSize =~ s/(.)/sprintf("%02x",ord($1))/eg; $fileName =~ s/\0+$//; printf "Loc: %d, Size: %d, Name: '%s'\n", $fileLoc, $fileSize, $fi +leName; }

Prints:

Using unpack Loc: 1, Size: 2, Name: 'The end of the world is neigh ' Loc: 3, Size: 4, Name: 'unless you use pack and unpack ' Using bogus substitution code Loc: -1, Size: -1, Name: 'The end of the world is neigh ' Loc: -1, Size: -1, Name: 'unless you use pack and unpack '

Note that I was using a build of Perl that doesn't have support for the quad word pack/unpack specification so I used the "VAX" long (32 bit) V specification and ignored the high words (that's the undefs in the variable list).

Oh, and the trailing spaces on the two "file name" lines in the sample data are important. Don't lose them copying this test script!

Perl is the programming world's equivalent of English

Replies are listed 'Best First'.
Re^4: sending data thru a sub routine
by AnomalousMonk (Archbishop) on May 12, 2014 at 06:13 UTC
    'The end of the world is neigh '

    So Eliot should have written "This is the way the world ends/Not with a bang but a whinny"?

Re^4: sending data thru a sub routine
by james28909 (Deacon) on May 15, 2014 at 01:25 UTC
    i love regex xD