Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Help with parsing a string

by sdolancu (Initiate)
on Jul 22, 2008 at 20:53 UTC ( #699425=perlquestion: print w/replies, xml ) Need Help??

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 |&
#!/usr/bin/perl # Name: # 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:

    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



    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):

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://699425]
Approved by moritz
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2023-05-29 22:48 GMT
Find Nodes?
    Voting Booth?

    No recent polls found