home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.perl
- Path: sparky!uunet!gatech!darwin.sura.net!convex!convex!tchrist
- From: Tom Christiansen <tchrist@convex.COM>
- Subject: Re: Case dependent substitution
- Originator: tchrist@pixel.convex.com
- Sender: usenet@news.eng.convex.com (news access account)
- Message-ID: <1992Sep9.235921.13124@news.eng.convex.com>
- Date: Wed, 9 Sep 1992 23:59:21 GMT
- Reply-To: tchrist@convex.COM (Tom Christiansen)
- References: <1992Sep9.191433.25724@uvaarpa.Virginia.EDU>
- Nntp-Posting-Host: pixel.convex.com
- Organization: Convex Computer Corporation, Colorado Springs, CO
- X-Disclaimer: This message was written by a user at CONVEX Computer
- Corp. The opinions expressed are those of the user and
- not necessarily those of CONVEX.
- Lines: 69
-
- From the keyboard of noran!iowa!kburton@uunet.uu.net:
- :
- :I would like to substitute an arbitrary pattern for another, but it all of
- :the alphabetic characters in the source pattern are upper case I would like
- :to case the replacement pattern to also force upper case substitution.
- :
- :For example:
- :
- : substitute "abc" in "ABCxyzabc" with "xyz" produces "XYZxyzxyz"
- : substitute "abc" in "abcxyzABC" with "xyz" produces "xyzxyzXYZ"
- :
- :I have started to work on a solution that first searches the string for pattern
- :matches, checks the mathched patten, then finally makes the appropriate
- :substitution. This "brute force" method doesn't seem very elegant or efficient
- :and I was wondering if any of the more experienced perl users could give me
- :a tip ?
-
- I've often wanted a /I switch that behaved this way. Here's
- what I use:
-
- s/abc/&mapcase('xyz')/gie;
-
- where mapcase is as follows:
-
- sub mapcase {
- local($lhs, $rhs) = ($&, shift);
- for (local($i) = 0; $i < length($lhs); $i++) {
- substr($lhs, $i, 1) =~ tr/A-Z//
- ? substr($rhs, $i, 1) =~ tr/a-z/A-Z/
- : substr($rhs, $i, 1) =~ tr/A-Z/a-z/;
- }
- $rhs;
- }
-
- You could do better if you hand-rolled it, because you could
- save how the mapping works and not check the lhs each time
- again and again.
-
- But it's not entirely satisfactory. Consider
-
- $_ = "Green is the green apple who has GREEN WORMS\n";
- print;
- s/green/&mapcase3('red')/gie;
- print;
-
- print "\n";
-
- $_ = "Red is the red apple who has RED WORMS\n";
- print;
- s/red/&mapcase3('green')/gie;
- print;
-
-
- Yields:
-
- Green is the green apple who has GREEN WORMS
- Red is the red apple who has RED WORMS
-
- Red is the red apple who has RED WORMS
- Green is the green apple who has GREen WORMS
-
- Hmm. I don't thing GREen is what you want here.
-
- --tom
- --
- Tom Christiansen tchrist@convex.com convex!tchrist
-
- If you want your program to be readable, consider supplying the argument.
- --Larry Wall in the perl man page
-