Scyld de Fraud
Scyld de Fraud

Reputation: 225

Get rid of special characters from perl string

I have this string:

$x = \x02 . 'raz' . \x02;

How to clean this up to have only "raz" ?

I try this:

$x =~ s/^[a-zA-z0-9,]//g;

but I would get:

SCALAR0x560917295870razSCALAR0x560917295900

how to get just "raz"?

Upvotes: 2

Views: 171

Answers (1)

ikegami
ikegami

Reputation: 385645

If you had the 5-character string produced by "\x02" . 'raz' . "\x02", then the following would work:

$x =~ s/[^a-zA-z0-9,]//g;

Note how I moved the ^.

Outside of a character class ([...]), it means "start of string" (or "start of line" when /m is used).

But as the first character of a character class ([^...]), it negates the character class. It will match all characters except those listed.


\x02 . 'raz' . \x02, on the other hand, produces a string of the form SCALAR(0xXXX)razSCALAR(0xXXX).

$ perl -M5.010 -e'say \x02 . "raz" . \x02;'
SCALAR(0x565362191c08)razSCALAR(0x565362163750)

You could use

$x =~ s/SCALAR\([^()]*\)//g;

Note that you should always use use strict; use warnings;. This would have avoided the situation that lead to the garbage being created in the first place.

Upvotes: 3

Related Questions