figgy has asked for the wisdom of the Perl Monks concerning the following question:

I have quite a dozen of repeated formulas
$list_total_perla+= $perla; $list_total_perlb+= $perlb; $list_total_perlc+= $perlc; $list_total_perld+= $perld; $list_total_perle+= $perle; $list_total_perld+= $perld;
Tried using an array
@shorten = (perla, perlb, perlc, perld, perle, perld);
to shorten the formula. But I am having difficulty calling the variables e.g. $list_total_perld

Replies are listed 'Best First'.
Re: Shorten the list of computation
by BrowserUk (Patriarch) on May 12, 2003 at 06:16 UTC

    Instead of using loads of seperate variable, use arrays:

    my ( @list_total_perl, @perl ); @perl = list_from_wherever(); $list_total_perl[ $_ ] += $perl[ $_ ] for 0 .. $#perl;

    Or if you insist on indexing things with letters, use hashes.

    my ( %list_total_perl, %perl ); @perl{ 'a' .. 'e' } = list_from_wherever(); $list_total_perl{ $_ } += $list{ $_ } for 'a' .. 'e';

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
Re: Shorten the list of computation
by Zaxo (Archbishop) on May 12, 2003 at 06:14 UTC

    You appear to use 'a'..'e' as labels indicating some order. An array, @list_totals, would make that much tidier, or else a hash if the labels are meaningful. Your variable names seem to edge toward symbolic references in design, which is not the way to go with it.

    After Compline,
    Zaxo

Re: Shorten the list of computation
by Aristotle (Chancellor) on May 12, 2003 at 06:05 UTC
    It's completely unclear what your problem is. What are you trying to do, what does not work as expected, and what does happen?

    Makeshifts last the longest.

Re: Shorten the list of computation
by CombatSquirrel (Hermit) on May 13, 2003 at 15:24 UTC
    If your variables have utterly different names and completely different purposes, which prevents from putting them into one array, you might want to use something like
    { no strict 'refs'; my @incs = qw( index chapter index pages names ); for my $i (@incs) { ${"total_$i"} += $$i; } }
    It would still be better if you first built up an hash with hard references and then iterate through the command list
    my %incs = (index => [ \$index, \$total_index ], chapter => [ \$chapter, \$total_chapter ], pages => [ \$pages, \$total_pages ], names => [ \$names, \$total_names ] ); my @incs = qw( index chapter index pages names ); ${$incs{$_}->[1]} += ${$incs{$_}->[0]} for (@incs);
    This does not violate use strict (assuming that you have declared all your variables before);