in reply to print perl arrays using variables in array name
G'day gsc,
Welcome to the Monastery.
Please wrap code and data in <code>...</code> tags. We're seeing '$array{$i}[2]' (with the '2' being a link); however, you presumably typed '$array{$i}[[2]]'. Please see "Writeup Formatting Tips" for more about this.
You appear to be confusing arrays (e.g. @array0) with hashes ($array{$i}[2] indicates the hash, %array, exists somewhere in your code).
Arrays are zero-based on Perl. You've used an index of 2 but write "Value1": the 1st element in the array has an index of 0; the 3rd element in the array has an index of 2.
I suspect you want to create variable names as if they were strings. This is a bad idea and you're code isn't even close to achieving this. Instead, use a hash and create key names which are strings.
Always use the strict and warnings pragmata. Had you done this, Perl would have told you about problems. Put these lines at the top of your scripts:
use strict; use warnings;
For one-liners, replace '-e' with '-wE': it's not exactly the same but is usually sufficient. You'll need at least Perl v5.10.0 to use the '-E' switch; if you don't have that, use "perl ... -we 'use strict; ...'". See "perlrun: Command Switches" for details.
Given the number of fundamental mistakes you've made, I strongly recommend that you read "perlintro: Perl introduction for beginners" — it's not long and should get you at least started with Perl code that compiles and runs correctly.
Here's my best guess at what your posted one-liner should look like:
$ perl -wlE 'my %h = (a0 => [1,2,3,4], a1 => [5,6,7,8]); print qq{A $_ +\nVal3 $h{"a" . $_}[2]} for (0,1)' A 0 Val3 3 A 1 Val3 7
Here it is again, this time as a script, with somewhat more meaningful variable and key names, and, hopefully, far more comprehensible:
#!/usr/bin/env perl -l use strict; use warnings; my %hash = ( array0 => [1, 2, 3, 4], array1 => [5, 6, 7, 8] ); for my $i (0, 1) { print "ARRAY $i"; print 'Value3 ', $hash{'array' . $i}[2]; }
Output:
ARRAY 0 Value3 3 ARRAY 1 Value3 7
— Ken
|
|---|