I have a situation where I need to remove the last n
numeric characters after a /
character.
For eg:
/iwmout/sourcelayer/iwm_service/iwm_ear_layer/pomoeron.xml@@/main/lsr_int_vnl46a/61
After the last /
, I need the number 61 stripped out of the line so that the output is,
/iwmout/sourcelayer/iwm_service/iwm_ear_layer/pomoeron.xml@@/main/lsr_int_vnl46a/
I tried using chop, but it removes only the last character, ie. 1, in the above example.
The last part, ie 61, above can be anything, like 221 or 2 or 100 anything. I need to strip out the last numeric characters after the /
. Is it possible in Perl?
The chop() function in Perl is used to remove the last character from the input string.
We can use the chop() method to remove the last character of a string in Perl. This method removes the last character present in a string. It returns the character that is removed from the string, as the return value.
length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.
Concatenate strings by inserting a fullstop (.) operator between them. Perl will automatically 'stringify' scalar variables that were initialised as a number.
A regex substitution for removing the last digits:
my $str = '/iwmout/sourcelayer/iwm_service/iwm_ear_layer/pomoeron.xml@@/main/lsr_int_vnl46a/61';
$str =~ s/\d+$//;
\d+
matches a series of digits, and $
matches the end of the line. They are replaced with the empty string.
@Tim's answer of $str =~ s/\d+$//
is right on; however, if you wanted to strip the last n digit characters of a string but not necessarily all of the trailing digit characters you could do something like this:
my $s = "abc123456";
my $n = 3; # Just the last 3 chars.
$s =~ s/\d{$n}$//; # $s == "abc123"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With