I have a script that reads STDIN by setting $/ to \16 and uses while (<>) to read 16 bytes at a time, then outputs the hex values of each byte. On MS-Dos based systems, it needs to read STDIN in binmode in order to represent the line-ends correctly. This works if the script is invoked with the < operator to feed the file in, or fed from a pipe, but if the file name is passed as a parameter, the (<>) magic does not respect the binmode setting.
This script is in a .cmd file so it can be invoked directly from the Command Prompt. Ignore everything up to the use strict; as this is a standard Perl/Batch polyglot.
@rem = '--*-Perl-*--
@echo off
perl "%~dpnx0" %1 %2 %3 %4 %5 %6 %7 %8 %9
goto endofperl
@rem ';
#!perl
#line 8
use strict;
use warnings;
binmode(STDIN);
$/ = \16;
my $line = '';
my $len = 0;
my $offset=0;
my $offhex='';
my $ord=0;
my $hex='';
my $char='';
print <<HEAD;
Offset 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 0123456789A
+BCDEF
-------- ----------------------------------------------- -----------
+-----
HEAD
format STDOUT =
@<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<
+<<<<<
$offhex, $hex, $char,
.
while (<>) {
$len = length;
$offhex = sprintf('%08X', $offset);
$hex = '';
$char = '';
foreach (split (//)){
$ord = ord($_);
$hex .= sprintf('%02X ', $ord);
$char .= ($ord > 13 or $ord < 7) ? $_ : ".";
}
write;
$offset += $len;
}
__END__
:endofperl
Update: If I set the environment variable PERLIO=:raw as per ysth's suggestion, it works for files passed as parameters. This breaks redirected input, though! So, my script just tests %1 and only sets the PERLIO variable if there is a parameter.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.