in reply to Rearranging a string

I see the pattern that muppetBoy is looking for ... but my solution is not particularly elegant.

The pattern is to pop off two bytes, reverse them, and then append them to a new string. If only one byte is left at the end, prepend an 'F' to it, and append that combination.

My clunky solution that is beggin' to be improved upon:

my @bytes = split (/([0-9A-F]{2})/, "0102030405060A0BC"); my $new; foreach (@bytes) { next if $_ eq ''; $new .= (length($_)==2) ? reverse($_) : 'F' . $_; } print $new, "\n";
I thought I knew split well enough, but apparently not as the @bytes array has empty elements in it (hence the hack to check if $_ is empty).

Replies are listed 'Best First'.
RE: Re: Rearranging a string
by ZZamboni (Curate) on Jul 03, 2000 at 21:42 UTC
    If this is the case, another way of doing it would be:
    $s='0102030405060A0BC' # Fix to even number of chars $s.=(length($s)%2?"F":"") for($i=0; $i<length($s); $i+=2) { substr($s,$i,2)=reverse(substr($s,$i,2)); }
    jeffa: you were getting empty elements because the two-character pairs are being used as delimiters, with empty elements between them.

    --ZZamboni

RE: Re: Rearranging a string
by nardo (Friar) on Jul 03, 2000 at 21:05 UTC
    The reason you are getting empty elements in @bytes is because there is nothing in between your delimiters (i.e. 01 and 02 are both delimiters and there is nothing between them). For a simpler example of this behavior, examine split(/x/, 'xxxxxxxxC') and split(/(x)/, 'xxxxxxxxC')