These functions are usually used when dealing with binary data: open, read, write, close, seek and binmode.
I've written this perl script to generate a random binary file:
#!/bin/perl -w use strict; use constant RANGE => 0xFF; if( $#ARGV != 1 ) { print "Error: no argument input!\n"; print "Usage: > perl $0 FILE_NAME MAX_BYTES\n"; print "Example: > perl $0 data.bin 255\n"; exit; } my $file = $ARGV[0]; my $max_bytes = $ARGV[1]; my $cnt = 0; open FILE,">", $file or die $!; while( $cnt < $max_bytes ) { print FILE chr(int(rand(RANGE))); ++$cnt; } close FILE; print "Binary file '$file' ($max_bytes bytes) generated!\n";binmode() is not in used, so how does it work? Because I generate random value in ASCII so I can easily convert it into its according character, then simply write into file. It does sound weird but it actually works! The case of using binmode() and just print the number, it doesn't write the binary as expected. I don't understand why ???? The next script is to read a binary file and print out the hex code of each character inside.
#!/bin/perl -w use strict; if( @ARGV != 2 ) { print "Error: wrong arguments input!\n", "Usage: > perl $0 FILE BYTES\n", "Example: > perl $0 data.bin 255\n"; exit; } my $file = $ARGV[0]; my $bytes = $ARGV[1]; open FILE, "<", $file or die $!; #binmode FILE; my $cnt = 0; while( $cnt < $bytes ) { read FILE, my $byte, 1; print sprintf("%02X", ord($byte)). " "; ++$cnt; } close FILE; print "\n";
I use read() to get each byte then re-format into hex then print().
I don't use binmode() but it still does work well.
So I think I just don't need binmode() even though it's a binary case.