Perl Cd Bookshelf [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Perl Cd Bookshelf [Electronic resources] - نسخه متنی

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید



4.6. Iterating Over an Array by Reference


4.6.1. Problem



You have a reference to an array,
and you want to use a loop to work with the array's
elements.

4.6.2. Solution


Use foreach or for to loop over
the dereferenced array:

# iterate over elements of array in $ARRAYREF
foreach $item (@$ARRAYREF) {
# do something with $item
}
for ($i = 0; $i <= $#$ARRAYREF; $i++) {
# do something with $ARRAYREF->[$i]
}

4.6.3. Discussion


The solutions assume you have a scalar variable containing the array
reference. This lets you do things like this:

@fruits = ( "Apple", "Blackberry" );
$fruit_ref = \@fruits;
foreach $fruit (@$fruit_ref) {
print "$fruit tastes good in a pie.\n";
}
Apple tastes good in a pie.
Blackberry tastes good in a pie.

We could have rewritten the foreach loop as a
for loop like this:

for ($i=0; $i <= $#$fruit_ref; $i++) {
print "$fruit_ref->[$i] tastes good in a pie.\n";
}

Frequently, though, the array reference is the result of a more
complex expression. Use the @{
EXPR } notation to turn the
result of the expression back into an array:

$namelist{felines} = \@rogue_cats;
foreach $cat ( @{ $namelist{felines} } ) {
print "$cat purrs hypnotically..\n";
}
print "--More--\nYou are controlled.\n";

Again, we can replace the foreach with a
for loop:

for ($i=0; $i <= $#{ $namelist{felines} }; $i++) {
print "$namelist{felines}[$i] purrs hypnotically.\n";
}

4.6.4. See Also


perlref(1) and perllol(1);
Chapter 8 of Programming Perl;
Recipe 11.1; Recipe 4.5



4.5. Iterating Over an Array4.7. Extracting Unique Elements from a List




Copyright © 2003 O'Reilly & Associates. All rights reserved.

/ 875