File Coverage

blib/lib/Data/HexDump/XXD.pm
Criterion Covered Total %
statement 40 40 100.0
branch 5 8 62.5
condition 3 3 100.0
subroutine 8 8 100.0
pod 2 2 100.0
total 58 61 95.0


line stmt bran cond sub pod time code
1             package Data::HexDump::XXD;
2              
3 3     3   71483 use version; our $VERSION = qv('0.1.1');
  3         6256  
  3         18  
4              
5 3     3   226 use warnings;
  3         6  
  3         83  
6 3     3   13 use strict;
  3         15  
  3         67  
7 3     3   16 use Carp;
  3         4  
  3         270  
8              
9 3     3   15 use base 'Exporter';
  3         4  
  3         1832  
10              
11             our @EXPORT_OK = qw( xxd_pack xxd_r xxd_unpack xxd );
12              
13             # Other recommended modules (uncomment to use):
14             # use IO::Prompt;
15             # use Perl6::Export;
16             # use Perl6::Slurp;
17             # use Perl6::Say;
18             # use Regexp::Autoflags;
19             # use Readonly;
20              
21             # Module implementation here
22             sub _xxd_line { # format a hex dump a-la xxd
23 32     32   110 my ($counter, @octets) = @_;
24 32         54 $counter = sprintf '%07x:', $counter;
25 32         30 my ($hex, $dump);
26 32         39 my @sep = ('', ' ');
27 32         56 for my $i (0 .. $#octets) {
28 507         739 $hex .= unpack('H*', $octets[$i]) . $sep[$i % 2];
29 507         529 my $code = ord $octets[$i];
30 507 100 100     1510 $dump .= ($code >= 0x20 && $code < 0x7F) ? $octets[$i] : '.';
31             }
32              
33 32         51 $hex .= ' ' x (40 - length $hex);
34 32         115 return join ' ', $counter, $hex, $dump;
35             } ## end sub _xxd_line
36              
37             sub xxd {
38 2     2 1 1434 my $length = length $_[0];
39 2         4 my $offset = 0;
40 2         3 my @retval;
41 2         7 while ($offset < $length) {
42 32         145 push @retval,
43             _xxd_line($offset, split //, substr $_[0], $offset, 16);
44 32         117 $offset += 16;
45             }
46 2 50       7 return @retval if wantarray;
47 2         22 return join "\n", @retval;
48             } ## end sub xxd
49             *xxd_unpack = \&xxd;
50              
51             sub xxd_r {
52 2     2 1 1578 my @retval;
53 2 50       24 for my $line (scalar(@_) > 1 ? @_ : split /\n/, $_[0]) {
54 32         218 my ($payload) = $line =~ m{\A\S+:\s (.*?) \s\s}xms;
55 32 50       62 next unless defined $payload;
56 32         454 $payload =~ s/\s//g;
57 32         94 push @retval, pack 'H*', $payload;
58             }
59 2         24 return join '', @retval;
60             } ## end sub xxd_r
61             *xxd_pack = \&xxd_r;
62              
63             1; # Magic true value required at end of module
64             __END__