http://qs321.pair.com?node_id=699425

sdolancu has asked for the wisdom of the Perl Monks concerning the following question:

I have an executable that outputs to STDERR and STDOUT the following:
00 0A EF 85 BA 8F AA BC
(and it keeps going for a while until an end of line character)

I built a perl script I want to pipe this output into. So to run it I would do the

Extractor.exe |& output.pl
#!/usr/bin/perl # Name: output.pl # while (<>) next if !~ m/([0-9a-f])([0-9a-f]) ([0-9a-f])([0-9a-f])/; $a = sprintf("%s%s%s%s",$1,$2,$3,$4); }
This is so ugly! And to do this for my whole "line" of output, I have to do like fifty captures. I was hoping someone had a more efficient way of doing this. Help please. Thanks, S

Replies are listed 'Best First'.
Re: Help with parsing a string
by moritz (Cardinal) on Jul 22, 2008 at 21:05 UTC
    It seems that you're just trying to remove all whitespaces:
    s/\s+//g;

    Of course that doesn't verify your data, so you could use split instead (untested):

    OUTER: while (<>){ chomp; my @items = split m/\s/; for my $i (@items) { last OUTER unless $i =~ m/^[a-f\d]{2}$/; } print join '', @items; }
      If you lines contain other text besides the hex numbers, you can restrict the space removal to just between the hex numbers with:
      $line =~ s{\b([a-f\d]{2})\s+(?=[a-f\d]{2}\b)}{$1}gi;
Re: Help with parsing a string
by GrandFather (Saint) on Jul 22, 2008 at 21:38 UTC

    Well, you could:

    use strict; use warnings; my $byte = qr/([0-9a-f]{2})/i; while (<DATA>) { my $line = join '', /\b$byte\b/g; next unless length $line; print "$line\n"; } __DATA__ 00 0A EF 85 BA 8F AA BC Wibble 00 0A EF 85 BA 8F AA BC

    Prints:

    000AEF85BA8FAABC 000AEF85BA8FAABC

    Perl is environmentally friendly - it saves trees
Re: Help with parsing a string
by jethro (Monsignor) on Jul 22, 2008 at 21:14 UTC
    Well, if you want to print those 4 chars, just do
    print $1,$2,$3,$4;
    Even better, if all you want is just to eliminate spaces in that string, do
    s/ //g; print;
    If that is not what you want, you have to be more specific.
Re: Help with parsing a string
by toolic (Bishop) on Jul 23, 2008 at 01:09 UTC
    Yet another way to represent a hexadecimal digit is to use the POSIX character class (see perlre):
    [[:xdigit:]]