Latest LQ Deal: Complete CCNA, CCNP & Red Hat Certification Training Bundle
Go Back > Forums > Non-*NIX Forums > Programming
User Name
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.


  Search this Thread
Old 07-22-2011, 02:04 AM   #1
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?


I'm reading "OReilly Learning Perl 5th Edition", and there are such words:
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:
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?

Old 07-22-2011, 09:58 AM   #2
Senior Member
Registered: Feb 2011
Location: Massachusetts, USA
Distribution: CentOS 6 (pre-systemd)
Posts: 2,801

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

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

$VAR1 = [
An array element doesn't have the capability to be used as an alias.


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 > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:36 PM.

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