-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Arvin Portlock <> wrote in news:besdb4$1a02$1
@agate.berkeley.edu:
> 1. Grepping an array of references possible?
....
>
> my $ref = {};
> $ref->{title} = 'Gone with the wind';
> $ref->{date} = '1952';
> push @books, $ref;
> my @mybooks;
> foreach my $book (@books) {
> if ($book->{title} =~ /Gone/) {
> push @mybooks, $book;
> }
> }
@mybooks = grep $_->{title} =~ /Gone/, @books;
>
> How would I use grep () in a scalar context if I just wanted
> to know how many books contained "Gone" and didn't want to
> create a new array?
$num = grep $_->{title} =~ /Gone/, @books;
> How about if I only wanted to know whether
> the array contained ANY book whose title contained that word,
if (grep $_->{title} =~ /Gone/, @books) { ...}
But you're right, a foreach loop is not a bad way to do that, especially
if the list is large, and you use 'last' once you have found a match.
> 2. Replacing elements of an array of references.
....
>
> my $new_edition = {};
> $new_edition->{title} = 'Gone with the wind';
> $new_edition->{date} = '2003';
> for (my $i = 0; $i++; $i <= $#books) {
> $books->[$i] = $new_edition if $books->[$i]->{title}
> eq 'Gone with the wind';
> }
>
> Any way to do this with grep ()?
No; a foreach loop is your best bet here:
foreach my $book (@$books)
{
$book = $new_edition if $book->{title} eq '....';
}
- --
Eric
$_ = reverse sort qw p ekca lre Js reh ts
p, $/.r, map $_.$", qw e p h tona e; print
-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 7.0.3 for non-commercial use <http://www.pgp.com>
iQA/AwUBPxHLkmPeouIeTNHoEQIYRACeN8hFSv1+6HlLNrHju1jqd4 lHO3AAoPn2
hYnPru0bZbhNYPFSlmAk8oBw
=+f9C
-----END PGP SIGNATURE-----
|