[comp.lang.perl] apply in Perl?

victor@arnor.uucp (02/14/91)

Is there something like the lisp apply in perl?  It seems like the
function grep is almost there.  For example, suppose that I want to
produce an array like the following:

foreach (1..$limit) {$a[$_ -1] = "foobar.$f";}

Of course I'd like to produce this array without giving it a name.  It
seems that grep("foobar.$f",(1..$limit)) actually evaluates these
things, and then throws them away.  Is there some hack to use grep (or
maybe something else) to actually produce the array?
--
			Victor S. Miller
			Vnet and Bitnet:  VICTOR at WATSON
			Internet: victor@ibm.com
			IBM, TJ Watson Research Center

victor@arnor.uucp (02/14/91)

Is there something like the lisp apply in perl?  It seems like the
function grep is almost there.  For example, suppose that I want to
produce an array like the following:

foreach (1..$limit) {$a[$_ -1] = "foobar.$f";}

Of course I'd like to produce this array without giving it a name.  It
seems that grep("foobar.$_",(1..$limit)) actually evaluates these
things, and then throws them away.  Is there some hack to use grep (or
maybe something else) to actually produce the array?
--
			Victor S. Miller
			Vnet and Bitnet:  VICTOR at WATSON
			Internet: victor@ibm.com
			IBM, TJ Watson Research Center

allbery@NCoast.ORG (Brandon S. Allbery KB8JRR) (02/18/91)

As quoted from <VICTOR.91Feb13112228@irt.watson.ibm.com> by victor@arnor.uucp:
+---------------
| foreach (1..$limit) {$a[$_ -1] = "foobar.$f";}
| 
| Of course I'd like to produce this array without giving it a name.  It
| seems that grep("foobar.$_",(1..$limit)) actually evaluates these
| things, and then throws them away.  Is there some hack to use grep (or
| maybe something else) to actually produce the array?
+---------------

It's not clear to me what you're trying to accomplish.  Maybe

	grep(push(@a, "foobar.$_"), (1 .. $limit));

which creates the same array as your foreach example.  Or, more concisely,

	@a = grep("foobar.$_", (1 .. $limit));

(Grep returns all "true" values, meaning anything that is not either numeric 0
or an empty string, generated by the expression.)

If you want to built it and act on it immediately, just use the value of the
grep:

	foreach (grep("foobar.$_", (1 .. $limit)))
	{
	    # this executes for each generated value, with the value in $_
	}

++Brandon
-- 
Me: Brandon S. Allbery			    VHF/UHF: KB8JRR on 220, 2m, 440
Internet: allbery@NCoast.ORG		    Packet: KB8JRR @ WA8BXN
America OnLine: KB8JRR			    AMPR: KB8JRR.AmPR.ORG [44.70.4.88]
uunet!usenet.ins.cwru.edu!ncoast!allbery    Delphi: ALLBERY