Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

looping through variables

by keiusui (Monk)
on Jul 04, 2006 at 02:50 UTC ( #559074=perlquestion: print w/replies, xml ) Need Help??
keiusui has asked for the wisdom of the Perl Monks concerning the following question:

I have five variables called $website_1, $website_2, $website_3, $website_4 and $website_5.

Is there a way to loop through these variables?

I tried the following to no avail:

for($x = 1; $x <= 5; $x++) { print $website_$x; }

Any help would be gratefully appreciated. Thank you.

Replies are listed 'Best First'.
Re: looping through variables
by davidrw (Prior) on Jul 04, 2006 at 02:55 UTC
    yes, but you're probably better off using an array or a hash (i had a discussion on this topic earlier today)..
    my @websites; print "Website = $_\n" for @websites;
    How are your variables currently being declared & populated?
      Also, you might consider this node: Here for a good description of why it is common, but a bad idea to do this kind of thing. I would just use an array for this, since it will probably not always be, say, 5 websites, but probably n. And if not, then just to get a bit of practice in writing good code (good habits build themselves, after a while).
Re: looping through variables
by GrandFather (Sage) on Jul 04, 2006 at 03:29 UTC

    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 = ''; $website_2 = ''; $website_3 = ''; # Populate array push @sites, "$" for 1 .. 3; # Populate hash $siteHash{"website_$_"} = "$" 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;


    Site 1 is Site 1 is Site 1 is Site Site Site Site 1 is Site 2 is Site 3 is Site website_1 is Site website_2 is Site website_3 is

    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

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

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

Re: looping through variables
by kwaping (Priest) on Jul 04, 2006 at 03:19 UTC
    I agree that an array would be a much better tool for this job. However, with that said, I'd like to show you how it could be done, if you were dead-set on doing it that way.
    use strict; use warnings; my $website_1 = 'a'; my $website_2 = 'e'; my $website_3 = 'i'; my $website_4 = 'o'; my $website_5 = 'u'; for (my $x = 1; $x <= 5; $x++) { print eval "\$website_$x"; }
    This is neither good nor safe, but I just wanted to show that it was indeed possible.

    It's all fine and dandy until someone has to look at the code.
      Teach people to be a good programmer, not to show off your stupid skill. You want him to be as stupid as you? The first reply already said the right thing, what are you doing here?
        Ananymous Monk,
        He already mentioned "This is neither good nor safe, but I just wanted to show that it was indeed possible. ".
        Then why you are telling him as stupid.This is for getting various solutions from various minds.If you know anymore answer post it,sothat we can also improve our knowledge.
Re: looping through variables
by ioannis (Monsignor) on Jul 04, 2006 at 04:55 UTC
    The standard way is to use symbolic references; provided, of course, that your variables are on the stash.
    no strict 'refs'; print ${ 'website_'. 3 };

      That's not the standard way, it's one of the standard mistakes.

      Decades of advances in computer science have gotten us to a point where dangerous practices such as "variable names for variables" (symbolic references) are usually superceeded by better, safer, saner alternatives. It's irresponsible to misrepresent symbolic references as the "standard way" to do something that really ought to be done with an array, a hash, or first class references.

      Just because Perl makes it possible to write fragile, bug prone, unsafe code doesn't mean doing so is necessarily the standard for Perl. To the contrary, living up to the standards of Perlish best practices dictates that the use of symbolic references is to be avoided in production code. Forget they exist, and you'll be in much better shape. Leave their use to the people who wrote Exporter, and other gluttons for punishment.

      I certanly hope the OP has the sense to listen to the voices of reason here, avoiding the use of symbolic references in favor of better strategies. I hope that your advice will be ignored, despite its apparent simplicity. That simplicity is dangerously seductive. The reality is that what appears simple at the outset can lead to hellish difficulty down the road.


        My post answered the question asked; without Sunday speeches.

        Anyone could advocate against symbolic references, but the fact remains that they remain useful, especially when exporting symbols to other namespaces - as a standard practice.

        There Shall Not Be One And Only One Responsible Way. This is Perl; when you don't know the right way , at least the many other ways that can prove useful: the lack of 'inferior' alternatives will yield you with nothing at all. The OP stood up and asked for solutions, he deserves to hear many answers.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://559074]
Approved by davidrw
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2018-05-20 20:47 GMT
Find Nodes?
    Voting Booth?