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

I wanted to know how to replace a char in a string. now, I know this string will come as the second string in each row, but I also know that the char I wish to replace is not unique (there might be other chars like it). however I wish to replace only the first char in that string from '0' to '2' Thannk

Replies are listed 'Best First'.
Re: Char replacement
by broquaint (Abbot) on Apr 02, 2003 at 12:26 UTC
Re: Char replacement
by dakkar (Hermit) on Apr 02, 2003 at 12:55 UTC

    "second string in each row" means exactly what?

    You have to perform two steps:

    1. find the beginning of that "second string"
    2. change its first char

    For step 2, you can use s///, tr///, or substr. Other have already said how.

    For step 1, it depends on how you separate strings. If your strings are separated by spaces (no quoting/escaping), I'd write: $line =~ s/^(\S+\s+)0/${1}2/; meaning:

    • match
      • ^ from the beginning of the line
      • ( remember the content of this
      • \S+ some non-spaces
      • \s+ some spaces
      • ) end remembering
      • 0 a literal zero
    • replace with
      • ${1} what you remembered in the match
      • 2 a literal 2

    -- 
            dakkar - Mobilis in mobile
    
Re: Char replacement
by Tomte (Priest) on Apr 02, 2003 at 12:08 UTC

    Read your way through perlre, pay particular attention to s///, or post some code to poke into.

    regards,
    tomte