in reply to String Substitution Operator

I'm not sure if I completely understand your question, partially because the regexps are obscured since code tags weren't used to preserve things like []. And partially because the text that came between "Now the question is this:" and the question mark, didn't really make sense to me.

From what I can tell, it looks to me like in the first regexp, you're only capturing with one set of parens. That means that $1 is the only variable that will have anything captured into it, in your first regexp. Nothing is populating $2 and $3. Also, $1 will only have something captured into it if the overall match was a success. Also, there is no need to use square brackets around \W if you're only matching one character, with a built-in character class. The square brackets are generally used to create custom character classes.

I hope this is of some help.

If your book gave you the regexp you have shown us, it would be a good candidate for the garbage heap. You might really get a lot out of perlretut, followed by perlfaq6, followed by perlre. Those three online POD's give a very thorough explanation of regular expressions, and start out (in perlretut) at a pace that isn't too overwhelming.

As far as what $1 $2 and $3 would "obviously" contain, I have no idea because you didn't provide the actual input string for us to see.

Your second regexp (the one that follows "THIS should work:" will substitute the first non-word character in the string with a hyphen. Is that what you meant by "work"? I might be missing something too. ;)


Dave


"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: String Substitution Operator
by hehenoobhehe (Novice) on Oct 23, 2003 at 08:42 UTC

    How do I :

    convert a string in day-month-year format to the dd-mm-yy format?

    I use :$string =~ s/(\W)/-/x;

    But the book asks me to use: $string =~ s/\d{2} ([\W]) \d{2} \1 \d{2}/$1-$2-$3/x instead and hence the confusion, since the special variables $1 etc will just match the pattern in parentheses, does this not mean that $1,$2,$3 should just contain the hyphen and NOT the *day*,*month*,*year* values?

    A related question is: if I do want to use the day,month,year values, how do I do that?

    Thanks.
      If I provide a string like "14/01/52", I want the output to be : "14-01-52".
        Simple.
        my $str = "14/01/52"; $str =~ s/\//-/g; # replace / with - print "$str\n";
        By using $string =~ s!/!-!g. The exclamation points prevent the "toothpick syndrome" (s/\//-/g is a little less readable).

        Arjen