in reply to looping through variables

Consider the following light weight comparison of various idioms:

use strict; use warnings; # Declare my ($website_1, $website_2, $website_3); my @sites; my %siteHash; # Populate vars $website_1 = 'www.site1.com'; $website_2 = 'www.site2.com'; $website_3 = 'www.site3.com'; # Populate array push @sites, "www.site$_.com" for 1 .. 3; # Populate hash $siteHash{"website_$_"} = "www.site$_.com" for 1 .. 3; # use individual sites print "Site 1 is $website_1\n"; print "Site 1 is $sites[0]\n"; print "Site 1 is $siteHash{website_1}\n\n"; # use site collections print "Site $_\n" for ($website_1, $website_2, $website_3); print "\n"; print "Site $_ is $sites[$_-1]\n" for 1 .. 3; print "\n"; print "Site $_ is $siteHash{$_}\n" for sort keys %siteHash;

Prints:

Site 1 is www.site1.com Site 1 is www.site1.com Site 1 is www.site1.com Site www.site1.com Site www.site2.com Site www.site3.com Site 1 is www.site1.com Site 2 is www.site2.com Site 3 is www.site3.com Site website_1 is www.site1.com Site website_2 is www.site2.com Site website_3 is www.site3.com

and note that individual variables don't really allow management as a collection (your problem) as both hashes and arrays do. Arrays don't give any help when accessing individual elements, but are suscinct. Hashes allow "symbolic" access to individual elements and management as a collection, but are a little more cumbersom.

You will perhaps have noticed that arrays and hashes of references have been omitted. If you are comfortable with those you probably wouldn't be asking the question. :)


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: looping through variables
by ikegami (Patriarch) on Jul 04, 2006 at 05:34 UTC

    print "Site $_ is $sites[$_-1]\n" for 1 .. 3;
    would be better written as
    print "Site $_ is $sites[$_-1]\n" for 1 .. @sites;
    or
    print "Site ", $_+1, " is $sites[$_]\n" for 0 .. $#sites;

    Noone said the index needed to be printed:
    print "$_\n" foreach @sites;