G'day...
Hello,
On Wed, 2004-11-24 at 23:00, FlashMX wrote:
Could you give an example of using grep on a array to do a replace?
grep example:
if (grep(/bazza/i, @myarray)) { print "Bazza's home!\n"; }
OR
my @bazza_list = grep {/bazza/i} @myarray;
(Either form is fine)
However to do a replace, I'd be more likely to use something like map.
grep is a search function... map can work well as a replacement function (I think of map as map one set of values to another set of values...)
E.g.
my @new_array = map { s/old/new/gi } @old_array;
Really map just goes through your list, mapping each item to $_ and performs the given expression on them...\
(Err.. I think the example above actually modifies the contents of @old_array ...)
Yes it does, and map returns the result of the substitution which is either 1 when it succeeds or '' when it fails.
$ perl -le'@x = 10 .. 29; print "@x\n"; @y = map { s/1/X/ } @x; print "@[EMAIL PROTECTED]"' 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 20 2X 22 23 24 25 26 27 28 29 1 1 1 1 1 1 1 1 1 1 1
You will have to return the value of $_ to make it work correctly.
my @new_array = map { s/old/new/gi; $_ } @old_array;
And if you want to do it without modifying @old_array:
my @new_array = map { ( my $x = $_ ) =~ s/old/new/gi; $x } @old_array;
John -- use Perl; program fulfillment
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>