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

hi all, timestmpa_value = "200504250955"

I would like to substitute 67 at the place 55. instead of 55
there may any numbers come.
but the timestamp length won't be changed

2006-04-26 Retitled by planetscape, as per Monastery guidelines
Original title: 'how to do the substitution'

  • Comment on How to replace the last 2 characters in a string

Replies are listed 'Best First'.
Re: How to replace the last 2 characters in a string
by bobf (Monsignor) on Apr 25, 2006 at 04:25 UTC

    If you want to replace the rightmost 2 digits, one way is by using substr:

    my $extracted_digits = substr( $var, -2, 2, $newdigits );

    For your specific example:

    use strict; use warnings; my $var = 200504250955; my $newdigits = 67; print "$var\n"; # 200504250955 my $extracted = substr( $var, -2, 2, $newdigits ); print "$var\n"; # 200504250967 print "$extracted\n"; # 55

Re: How to replace the last 2 characters in a string
by McDarren (Abbot) on Apr 25, 2006 at 04:27 UTC
    Let me re-phrase before I answer the question, in case I don't understand.

    "I wan't to replace the last two digits in a string with 67"

    In that case:

    $string =~ s/\d\d$/67/;

    May I suggest perlre and perlretut for more information.

Re: How to replace the last 2 characters in a string
by Samy_rio (Vicar) on Apr 25, 2006 at 04:28 UTC

    Try this,

    use strict; use warnings; my $timestmpa_value = "200504250955"; $timestmpa_value =~ s/.{2}$/67/; print $timestmpa_value;

    You should view How (Not) To Ask A Question

    Regards,
    Velusamy R.


    eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

Re: How to replace the last 2 characters in a string
by gube (Parson) on Apr 25, 2006 at 04:40 UTC
    #!/usr/local/bin/perl use strict; use warnings; my $timestmpa_value = "200504250955"; $timestmpa_value =~ s#\d{2}$#67#; print $timestmpa_value
Re: How to replace the last 2 characters in a string
by ashokpj (Hermit) on Apr 25, 2006 at 05:04 UTC

    try this one. it code will change all 55 into 67 at any place.

    my $timestmpa_value = "200554250955"; $timestmpa_value =~ s#55#67#g; print $timestmpa_value