views:

74

answers:

2

Consider this snippet:

use strict;
use warnings;

my $data = "1";
my $packed = pack("I",$data);
open(my $file,">","test.bin") || die "error $!\n";
binmode $file;
print $file $packed;

The thing is, trying to read it from another language, this appears to be little endian. Is there any template argument that allows me to write it as big endian? I'd like to avoid doing extra work when reading.

+4  A: 

Consider using the "N" template with pack:

http://perldoc.perl.org/functions/pack.html

Tim
+3  A: 

The solution is the N template.

my $packed = pack "N", $data;

See the pack documentation for a list of all pack options.

Leon Timmermans
As of Perl 5.10 you can also use byte-order modifiers (`<` and `>`). They aren't necessary here but they're a godsend for quad words and floating point.
Michael Carman
Nice tip, thanks! Seems that `I>` also produces the right result.
Geo