in reply to ascii problem

Sounds like a job for a regular expression:

#!/usr/bin/perl my $test = "hello there ass\x08\x08wesome"; print "BEFORE: $test, ", "(length: " . length($test) . ")\n"; while ($test =~ /\x08/) { $test =~ s/.\x08//; } print "AFTER: $test, ", "(length: " . length($test) . ")\n";

On my terminal that prints:

BEFORE: hello there awesome, (length: 23) AFTER: hello there awesome, (length: 19)

You'd need to use a hex editor (or if you're elite, hexl-mode in Emacs) to confirm that the first string actually had backspaces, but the lengths match my expectations.

The regular expression works by finding any character (.) followed by a backspace (\x08) and replacing them with nothing (i.e. deleting them from the string). This is wrapped up in a loop to repeat the process as long as backspaces are present.

-sam

Replies are listed 'Best First'.
Re^2: ascii problem
by davido (Cardinal) on Jun 01, 2006 at 21:00 UTC

    That's good, but somehow I just don't like seeing you needing to test with the m// operator, and then perform a nearly equal match for the substitution. To get away with invoking the regexp engine only one time instead of twice on each loop iteration, you can do this instead:

    use strict; use warnings; my $test = "hello there ass\x08\x08wesome"; print "BEFORE: $test, ", "(length: " . length($test) . ")\n"; while ($test =~ /.\x08/) { $test = substr( $test, 0, $-[0] ) . substr( $test, $+[0] ); # Note: The preceeding line is the same as: # $test = $` . $'; # but avoids using $` and $', side-stepping the global # performance penalty associated with their use. } print "AFTER: $test, ", "(length: " . length($test) . ")\n";

    Dave

        Bingo!
        It pays to take a fresh look, doesn't it? :)


        Dave