in reply to Re^2: hexdump -C
in thread hexdump -C

That is so cool! I modified it slightly so it also runs on TinyPerl 5.8:

sub hexdump { my $s; $_[0] =~ s/\G([\0-\xff]{1,16})/ $s = $1; $s =~ y|\x20-\x7e|.|c; spri +ntf("%08X %-50s|%s|\n", $-[0], "@{[unpack q{(H2)8a0(H2)8}, $1]}", $s +);/ge; return $_[0]; }

I don't understand why I had to do this: ([\0-\xff]{1,16}) instead of (.{16}) This latter one won't capture anything, which is weird. The second thing I don't understand is why this works:

"@{[unpack q{(H2)8a0(H2)8}, $1]}"

Replies are listed 'Best First'.
Re^4: hexdump -C
by ikegami (Patriarch) on Oct 15, 2025 at 14:15 UTC

    Maybe cause you were missing the /s? (It was also missing in the original code.)

    a0 returns a zero-length string. [ ] creates an anon array and returns a reference to is. @{ ... } is the referenced array. Interpolating an array in a string joins elements with spaces by default.

      Hmm... interesting! oh yes yes yes, I forgot the /s

      So, once again, here is the working code:

      #!/usr/bin/perl -w use strict; use warnings; @ARGV = ($0); print hexdump( join('', <>) ); sub hexdump { my $s; $_[0] =~ s/\G(.{1,16})/ $s = $1; $s =~ y|\x20-\x7e|.|c; sprintf("%08 +X %-50s|%s|\n", $-[0], "@{[unpack q{(H2)8a0(H2)8}, $1]}", $s);/ges; return $_[0]; }

        Since we're golfing,

        $s = $1; $s =~ y|\x20-\x7e|.|c;

        can be replaced with

        ( $s = $1 ) =~ y|\x20-\x7e|.|c;

        It's one character shorter with spaces removed.

        Or

        $s = $1 =~ y|\x20-\x7e|.|cr;

        It's yet another character shorter with spaces removed.

        Beware that you are modifying the scalar passed as $_[0]. You probably want to do:
        sub hexdump { (my $x= shift) =~ s/\G(.{1,16})/ (my $s= $1) =~ y|\x20-\x7e|.|c; sprintf "%08x %-50|%s|\n", $-[0], "@{[unpack q{(H2)8a0(H2)8},$1]}", $s /ges; $x }