[comp.lang.perl] Substitution shortcut?

Mike.McManus@FtCollins.NCR.com (Mike McManus) (09/06/90)

If I have something like this:

$a = "hello";
$b = $a;
$b =~ s/ello/i/;

...is there a "short" way to write this?  Something like:

$a = "hello";
$b = ($a ~ s/ello/i/);

Seems silly to have to say $b = $a first, but if I gotta, so be it.  Just
curious if I've been missing something.

Thanks!
--
Disclaimer: All spelling and/or grammar in this document are guaranteed to be
            correct; any exseptions is the is wurk uv intter-net deemuns,.

Mike McManus                        Mike.McManus@FtCollins.NCR.COM, or
NCR Microelectronics                ncr-mpd!mikemc@ncr-sd.sandiego.ncr.com, or
2001 Danfield Ct.                   uunet!ncrlnk!ncr-mpd!garage!mikemc
Ft. Collins,  Colorado              
(303) 223-5100   Ext. 378
                                    

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (09/07/90)

In article <MIKE.MCMANUS.90Sep6133949@mustang.FtCollins.NCR.com> Mike.McManus@FtCollins.NCR.com (Mike McManus) writes:
: 
: If I have something like this:
: 
: $a = "hello";
: $b = $a;
: $b =~ s/ello/i/;
: 
: ...is there a "short" way to write this?  Something like:
: 
: $a = "hello";
: $b = ($a ~ s/ello/i/);
: 
: Seems silly to have to say $b = $a first, but if I gotta, so be it.  Just
: curious if I've been missing something.

Recall that an assignment can be an lvalue.  So the idiom is

	$a = "hello";
	($b = $a) =~ s/ello/i/;

This is also quite useful with chop and tr///:

	chop($HOST = `hostname`);
	($host = $HOST) =~ tr/A-Z/a-z/;

Larry

merlyn@iwarp.intel.com (Randal Schwartz) (09/07/90)

In article <MIKE.MCMANUS.90Sep6133949@mustang.FtCollins.NCR.com>, Mike.McManus@FtCollins (Mike McManus) writes:
| 
| If I have something like this:
| 
| $a = "hello";
| $b = $a;
| $b =~ s/ello/i/;
| 
| ...is there a "short" way to write this?  Something like:
| 
| $a = "hello";
| $b = ($a ~ s/ello/i/);
| 
| Seems silly to have to say $b = $a first, but if I gotta, so be it.  Just
| curious if I've been missing something.

Pretty durn close.

($b = $a) =~ s/ello/i; # copy $a to $b, and then change $b

I use this idiom all the time, as in:

while (<>) {
	($upper = $_) = y/a-z/A-Z/;
	# now $upper has an uppercase version of line, with $_ still original
	...
}

($_ = "Just another") =~ s/$/ Perl hacker,/; print
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/