LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-22-2011, 02:04 AM   #1
password636
Member
 
Registered: Jun 2006
Location: Beijing
Posts: 60

Rep: Reputation: 1
Why Perl's foreach loop can't use an array element as the control variable?


Hi,

I'm reading "OReilly Learning Perl 5th Edition", and there are such words:
Code:
You can use an array element like $fred[2] in every place† where you could use any other scalar variable like $fred.
At the bottom of the page, it explains the † like this:
Code:
The most notable exception is that the control variable of a foreach loop, which you’ll see later in this chapter, must be a simple scalar.
Since Perl has the save-and-restore mechanism for the control variable, why an array element can't be used as the control variable?

THANKS!
 
Old 07-22-2011, 09:58 AM   #2
smallpond
Senior Member
 
Registered: Feb 2011
Location: Massachusetts, USA
Distribution: Fedora
Posts: 4,138

Rep: Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263
The control variable is not used as a simple scalar, it is an alias of the current loop variable. For example:

Code:
use Data::Dumper;
@foo=(1, 6, 5); 
foreach $i (@foo) {
  $i++;
}
print Dumper \@foo;

$VAR1 = [
          2,
          7,
          6
        ];
An array element doesn't have the capability to be used as an alias.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
conditional foreach loop in perl casperdaghost Programming 2 06-01-2010 04:23 PM
Perl - foreach loop reading only the last $scalar in a @list OldGaf Programming 3 08-08-2009 09:57 AM
[perl] copying an array element into another array s0l1dsnak3123 Programming 2 05-17-2008 01:47 AM
PERL - foreach array not clearing michael.barnes Programming 8 08-21-2007 09:37 PM
Perl: Where am I in a foreach loop? jrtayloriv Programming 3 01-30-2005 10:43 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:32 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration