Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Am trying to eliminate a character from an input

$output (" show interfaces terse | match $interface"); @outputlist = split /\s+/, $output; foreach my $element (@outputlist) { if ($element =~ /e-/) { $element = s/.\K.+//; push (@child_interfaces, $element); print "1.@child_interfaces\n"; }

In the above code, @outputlist will get say, xe-2/0/0.0, i want to remove the .0 from this value, it should be xe-2/0/0 . I tried with K ( to keep existing and remove values after .. Its not working. Tried few other substitution. Is there a way to remove .0

Replies are listed 'Best First'.
Re: String removal
by Athanasius (Cardinal) on Sep 15, 2015 at 14:28 UTC

    Is this what you’re trying to do?

    0:23 >perl -wE "my $s = 'xe-2/0/0.0'; $s =~ s{\..*}{}; say $s;" xe-2/0/0 0:23 >

    In a regex, . matches any character (other than a newline, unless the /s modifier is used). To specifically match a dot (period, full stop, decimal point), you need to escape it: \.

    Update:

    I tried with K ( to keep existing and remove values after

    Variable-length look-behind (using \K) could be useful if you wanted to match something specific but exclude it from the substitution. For example, to remove the dot and any characters following it, but only if the dot itself comes immediately after a digit, you could do this:

    s{\d\K\..*}{}

    See “Look-Around Assertions” in perlre#Extended-Patterns. But, then again, you could accomplish the same thing without \K by using a capture:

    s{(\d)\..*}{$1}

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks. Works great!

Re: String removal
by kennethk (Abbot) on Sep 15, 2015 at 14:31 UTC
    Please read How do I post a question effectively?. In particular, the code you've posted doesn't compile.
    $output (" show interfaces terse | match $interface");
    is not valid Perl.

    Regarding your original question, the likely cause of your issue is that . is a metacharacter in regular expressions that means 'Match any character'. If you want a literal ., you need to escape it with \, as described in Quoting metacharacters. You probably also want to anchor it to the end of the string with $.

    s/\.\d+$//;

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.