2

od -x test shows:

0000000 457f 464c 0102 0001

Now I want to use Perl to create such file.

open FH,'>','test_1';
#syswrite(FH,0x457f464c01020001); # not work
print FH 0x457f464c01020001;      # not work

How to create binary file in Perl?

1
  • For what it's worth, your code does "work", but it doesn't do what you want. It converts the hex representation to its internal number format (probably losing a bunch of bits in the conversion), then prints the decimal representation of the number. Think about it - you would hardly want print 1; to print a ctrl-A. Commented Feb 29, 2012 at 6:51

4 Answers 4

7

To create a binary file, one uses

open (my $fh, '>:raw', $qfn)

To place

45 7f 46 4c 01 02 00 01

in that file, one can use any of the following:

# Starting with a string of those bytes.
print $fh "\x45\x7f\x46\x4c\x01\x02\x00\x01";

# Starting with a hex representation of the file.
print $fh pack('H*', '457f464c01020001');

# Starting with the bytes.
print $fh map chr, 0x45, 0x7f, 0x46, 0x4c, 0x01, 0x02, 0x00, 0x01;

# Starting with the bytes.
print $fh pack('C*', 0x45, 0x7f, 0x46, 0x4c, 0x01, 0x02, 0x00, 0x01);
Sign up to request clarification or add additional context in comments.

Comments

2
open(my $out, '>:raw', 'test_1.bin') or die "Unable to open: $!";
print $out pack('s<',255) ;
close($out);

also you can look at the perl pack functions here

1 Comment

Alternative to set file to binary mode: binmode(FH); It's worth understanding what 's' represents (for OP): perldoc.perl.org/functions/pack.html
1
print FH pack 'H*', '457f464c01020001'

Comments

0

print FH "\x45\x7f\x46\x4c\x01\x02\x00\x01" is another way. See Quote and Quote-like Operators in perlop for more information about escape sequences available in strings. \x works like it does in C... except that Perl has an extended syntax that goes beyond \xff.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.