home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!dtix!darwin.sura.net!uvaarpa!mmdf
- From: noran!iowa!kburton@uunet.uu.net (Kevin Burton)
- Newsgroups: comp.lang.perl
- Subject: RE: Case dependent substitution
- Message-ID: <1992Sep10.194824.1145@uvaarpa.Virginia.EDU>
- Date: 10 Sep 92 19:48:24 GMT
- Sender: mmdf@uvaarpa.Virginia.EDU (Mail System)
- Reply-To: noran!iowa!kburton@uunet.uu.net
- Organization: The Internet
- Lines: 88
-
-
- Tom Christiansen writes:
-
- | 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;
- | }
- | .
- | .
- | .
- | 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
-
- Thanks for the reply it gave me enough to generate the solution that
- is as follows:
-
- sub mapcase {
- local($lhs, $rhs) = ($&, shift);
- local($i,$j);
-
- # the case of the target will match th case of the source
- for ($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/;
- }
-
- # Avoid getting GReen when substituting re5 with green
- while(substr($lhs, $i-1, 1) !~ tr/A-Za-z//)
- {
- $i--;
- }
- # Avoid getting GREen when substituting red with green
- for ($j = $i; $j < length($rhs); $j++)
- {
- substr($lhs, $i-1, 1) =~ tr/A-Z//
- ? substr($rhs, $j, 1) =~ tr/a-z/A-Z/
- : substr($rhs, $j, 1) =~ tr/A-Z/a-z/;
- }
-
- $rhs;
- }
-
- Thank you!
-
- -
-
- This is not an official statement of Noran Instruments. No warranty is
- expressed or implied. The information included herein is not to be construed
- as a committment on Noran's part.
-
- Kevin Burton
- Noran Instruments voice: (608) 831-6511 x317
- 2551 West Beltline Highway, Room 532 FAX: (608) 836-7224
- Middleton, WI 53562 email: kburton@noran.com
-