The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.
#!/usr/bin/env perl
use strict;
use warnings;
use Pod::Usage qw( pod2usage );
use Getopt::Long qw( :config gnu_getopt );
use version; my $VERSION = qv('0.0.1');
use Data::HexDump::XXD qw( xxd xxd_r );
use File::Slurp qw( slurp );

my %config = ();
GetOptions(\%config, 'usage', 'help', 'man', 'version',
   'plain|ps|postscript|p!', 'revert|r!');
pod2usage(message => "$0 $VERSION", -verbose => 99, -sections => '')
  if $config{version};
pod2usage(-verbose => 99, -sections => 'USAGE') if $config{usage};
pod2usage(-verbose => 99, -sections => 'USAGE|EXAMPLES|OPTIONS')
  if $config{help};
pod2usage(-verbose => 2) if $config{man};

# Script implementation here
my $indata = slurp(@ARGV ? $ARGV[0] : \*STDIN);

my $outdata;
if ($config{plain}) {    # no real need for xxd/xxd_r here
   if ($config{revert}) {
      $indata =~ s/\s+//mxsg;
      $outdata = pack 'H*', $indata;
   }
   else {
      $outdata = unpack 'H*', $indata;
      $outdata =~ s/(.{32})/$1\n/mxsg;
   }
} ## end if ($config{plain})
else {
   $outdata = $config{revert} ? xxd_r($indata) : xxd($indata);
}
$outdata .= "\n" unless $config{revert} || substr($outdata, -1) eq "\n";

binmode STDOUT;
print {*STDOUT} $outdata;

__END__

=head1 NAME

xxd - a minimal replacement for the *real* xxd program


=head1 VERSION

Just call

   shell$ xxd --version


=head1 USAGE

   xxd [--usage] [--help] [--man] [--version]

   xxd [--plain|-p] [--revert|-r] [filename]
  
=head1 EXAMPLES

   # Plain default behaviour
   shell$ xxd somefile.bin > somefile.hex

   # Go the other way
   shell$ xxd -r somefile.hex > somefile_regenerated.bin

   # You even have the "plain" option, as a bonus
   shell$ xxd -p somefile.bin > somefile.plainhex


  
=head1 DESCRIPTION

This example script can be used as a replacement for the B<xxd> utility
itself, except that it does not have all its features. Apart from not
supporting all the options, it also lacks devising consequent equal lines
and grouping them with the C<*> like the real B<xxd> does.


=head1 OPTIONS

Note that options in the original B<xxd> always begin with a single
hyphen, while options here start with a single hyphen for they short
(one-char) form, and with two hyphens in their long form. This allows
concatenation of switches (e.g. C<-rp> instead of C<-r -p>, which I
find annoying in B<xxd>).

=over

=item --help

print a somewhat more verbose help, showing usage, this description of
the options and some examples from the synopsis.

=item --man

print out the full documentation for the script.

=item --plain | -p

output in postscript continuous hexdump style. Also known as plain
hexdump style. (From xxd manual).

=item --revert | -r

reverse operation: convert hexdump into binary. Use the combination
C<-r -p> to read plain hexadecimal dumps without line number information
and without a particular column layout. Additional whitespace and
line-breaks are allowed anywhere. (From xxd manual, with adaptation).

=item --usage

print a concise usage line and exit.

=item --version

print the version of the script.

=back

=head1 CONFIGURATION AND ENVIRONMENT

xxd requires no configuration files or environment variables.


=head1 DEPENDENCIES

L<version> is a I<de facto> standard but still not in core as of 5.8.8,
so you'll need it (or you'll have to comment it out).

L<Getopt::Long> and L<Pod::Usage> should be no problem, because they're in
core.

So, what you will really need are L<File::Slurp> and, of course,
L<Data::HexDump::XXD>.

=head1 BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests through http://rt.cpan.org/

Only two options of the original B<xxd> are supported, but they should
be the most useful and used.

Consequent equal lines in dump are not grouped with C<*>.


=head1 AUTHOR

Flavio Poletti C<flavio@polettix.it>


=head1 LICENCE AND COPYRIGHT

Copyright (c) 2006, Flavio Poletti C<flavio@polettix.it>. All rights reserved.

This script is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>
and L<perlgpl>.

Questo script è software libero: potete ridistribuirlo e/o
modificarlo negli stessi termini di Perl stesso. Vedete anche
L<perlartistic> e L<perlgpl>.


=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

=head1 NEGAZIONE DELLA GARANZIA

Poiché questo software viene dato con una licenza gratuita, non
c'è alcuna garanzia associata ad esso, ai fini e per quanto permesso
dalle leggi applicabili. A meno di quanto possa essere specificato
altrove, il proprietario e detentore del copyright fornisce questo
software "così com'è" senza garanzia di alcun tipo, sia essa espressa
o implicita, includendo fra l'altro (senza però limitarsi a questo)
eventuali garanzie implicite di commerciabilità e adeguatezza per
uno scopo particolare. L'intero rischio riguardo alla qualità ed
alle prestazioni di questo software rimane a voi. Se il software
dovesse dimostrarsi difettoso, vi assumete tutte le responsabilità
ed i costi per tutti i necessari servizi, riparazioni o correzioni.

In nessun caso, a meno che ciò non sia richiesto dalle leggi vigenti
o sia regolato da un accordo scritto, alcuno dei detentori del diritto
di copyright, o qualunque altra parte che possa modificare, o redistribuire
questo software così come consentito dalla licenza di cui sopra, potrà
essere considerato responsabile nei vostri confronti per danni, ivi
inclusi danni generali, speciali, incidentali o conseguenziali, derivanti
dall'utilizzo o dall'incapacità di utilizzo di questo software. Ciò
include, a puro titolo di esempio e senza limitarsi ad essi, la perdita
di dati, l'alterazione involontaria o indesiderata di dati, le perdite
sostenute da voi o da terze parti o un fallimento del software ad
operare con un qualsivoglia altro software. Tale negazione di garanzia
rimane in essere anche se i dententori del copyright, o qualsiasi altra
parte, è stata avvisata della possibilità di tali danneggiamenti.

Se decidete di utilizzare questo software, lo fate a vostro rischio
e pericolo. Se pensate che i termini di questa negazione di garanzia
non si confacciano alle vostre esigenze, o al vostro modo di
considerare un software, o ancora al modo in cui avete sempre trattato
software di terze parti, non usatelo. Se lo usate, accettate espressamente
questa negazione di garanzia e la piena responsabilità per qualsiasi
tipo di danno, di qualsiasi natura, possa derivarne.

=cut