home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.perl
- Path: sparky!uunet!cs.utexas.edu!hellgate.utah.edu!lanl!newshost.lanl.gov!jgd
- From: jgd@acl.lanl.gov (Jerry G. DeLapp)
- Subject: Re: Avoiding intermediate variable
- In-Reply-To: stantz@sgi.com's message of 21 Aug 92 00:33:14 GMT
- Message-ID: <JGD.92Sep3145140@kodiak.acl.lanl.gov>
- Sender: news@newshost.lanl.gov
- Reply-To: jgd@acl.lanl.gov
- Organization: Advanced Computing Lab, LANL, NM
- References: <MARK.MCINTOSH.92Aug20145545@sombrio.UVic.CA>
- <1992Aug21.003314.13443@odin.corp.sgi.com>
- Date: Thu, 3 Sep 1992 21:51:40 GMT
- Lines: 53
-
- >>>>> On 21 Aug 92 00:33:14 GMT, stantz@sgi.com (Mark Stantz) said:
- Mark> Nntp-Posting-Host: sierra.corp.sgi.com
-
- Mark> In article <MARK.MCINTOSH.92Aug20145545@sombrio.UVic.CA> Mark.McIntosh@engr.UVic.CA (Mark McIntosh) writes:
- >Someone out my location would like to avoid the intermediate variable
- >in the following piece of code, assuming $y has been set to some value:
- >
- > $tmp = $y;
- > $tmp =~ s/xy/zz/;
- > print $tmp;
- >
- >He wants to retain the value of $y for later use but use a modified
- >version of it once - he won't need it later. Is there a way to do
- >this in Perl without using an intermediate variable?
-
- Mark> print ((($junk = $y) =~ s/xy/zz/) ? $junk : $y);
-
- Mark> should do the job. You need those outermost parentheses, BTW.
-
- Mark> print $junk if (($junk = $y) =~ s/xy/zz/);
-
- Well, you can do it with an automagically generated variable a'la:
-
- sub foo {
- print ($_[0],zz,$_[1]);
- }
- $y='gortxyflort';
- &foo($y=~/(.*)xy(.*)/);
- exit;
-
- or:
-
- $y='gortxyflub';
- $y=~/(.*)xy(.*)/;
- print $1,zz,$2;
- exit;
-
- There's still an intermediate variable used here, but I'm assuming the user
- objects to having to "invent" his own temporary variable. I've used the first
- trick extensively in a package here where the first character of a pattern is
- an optional single character switch, and the remainder is a pattern. Whenever
- I call a subroutine which doesn't care about the switch, I put a pattern like
-
- $var=~/^[abq](.*)/
-
- in the argument list, and voila, the pattern is handed into the subroutine
- sans the switch character, without destroying $var. This makes it easier to
- code the subroutine, because I can concentrate on the data value I want to
- manipulate, instead of worrying about the optional baggage.
- --
-
- Jerry G. DeLapp -- ACL System Scientist -- (505) 665-4531 <jgd@lanl.gov>
- Computing beyond the Bleeding Edge -- The Advanced Computing Laboratory
-