While working a problem this morning I came across a possible solution that involved assigning sequential values to an array element, doing something and then incrementing the value and doing it again. I wondered if such a think could be done using a foreach loop without a secondary assignment;
Based on my reading, I don't believe that what I want can be done. The foreach construct requires simple scalar variables. That being said, has anyone done it?
For example, a typical solution might be ...
my @tstary = (0,0,0,0,0);
print join(":",@tstary),"\n";
foreach my $idx1 (1..3){
$tstary[1] = $idx1;
print join(":",@tstary),"\n";
}
__OUTPUT__
0:0:0:0:0
0:1:0:0:0
0:2:0:0:0
0:3:0:0:0
This got me thinking, could I use the array elt itself. The foreach construct doesn't allow a array directly, so how about a referece/dereference ... something like
my @ary03 = (0,0,0,0,0);
print join(":",@ary03),"\n";
foreach ${$ary02[3]} (1..3){
$tstary[1] = $idx1;
print join(":",@tstary),"\n";
}
# this doesn't work with an error of
# Can't use string ("0") as a symbol ref while "strict refs" in use
# other variations didn't work either
# how about
$aryeltref = \$ary03[1];
foreach $aryeltref (1..3){
print join(":",(@tstary,$aryeltref)),"\n";
}
__OUTPUT__
0:0:0:0:0:SCALAR(0x2144a28)
0:0:0:0:0:1
0:0:0:0:0:2
0:0:0:0:0:3
# expected but not quite what I had in mind
# trying foreach $$aryeltref (1..3) produced a "Not a GLOB reference a
+t ... " which makes me wonder if some mojo with the symbol table migh
+t make it work?
Just a couple of thoughts on a rainy Thursday morning
By the way, I know I can use the three arg for construct for this. I'm just trying to push the boundary of the foreach construct a little
PJ
use strict; use warnings; use diagnostics;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.