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

Dear Monks,

How can i print the variable. my coding is
my $KPI0=10; my $KPI1=20; my $KPI2=30; my $KPI3=40; my $KPI4=50; for($i=0;$i<5;$i++){ my $var="$KPI$i"; print "line"."$var"."\n"; } my expected output is line10 line20 line30 line40 line50


Thanks in advance
Shanmugam A.

Replies are listed 'Best First'.
Re: how can print the variable values
by Corion (Patriarch) on Dec 01, 2008 at 11:29 UTC
Re: how can print the variable values
by ccn (Vicar) on Dec 01, 2008 at 11:28 UTC

    You should better to use an array

    my @KPI = (10, 20, 30, 40, 50); for my $i (0 .. $#KPI){ my $var = $KPI[$i]; print "line"."$var"."\n"; }
Re: how can print the variable values
by oko1 (Deacon) on Dec 01, 2008 at 13:32 UTC

    General rule of thumb: whenever you find yourself creating a collection of variables, you should use a hash (or occasionally an array) instead. Also, when you find yourself using a C-style 'for(;;)' loop, you should consider whether it's actually the right thing. Most times, it's not.

    ### Array # Indexes of 0-4 automatically assigned by Perl! my @kpi = qw/10 20 30 40/; print "line$kpi[$_]\n" for 0..4; ### Hash my %kpi; # Populating via hash slice to save typing @kpi{0..4} = qw/10 20 30 40 50/; print "line$kpi{$_}\n" for 0..4;

    --
    "Language shapes the way we think, and determines what we can think about."
    -- B. L. Whorf
Re: how can print the variable values
by JavaFan (Canon) on Dec 01, 2008 at 13:02 UTC
    Well, one of doing this (although I strongly recommend against this practise - not just this way, but using "names of variables" to get to the variables value in general) is:
    use warnings; use strict; our $KPI0 = 10; our $KPI1 = 20; our $KPI2 = 30; our $KPI3 = 40; our $KPI4 = 50; for (my $i = 0; $i < 5; $i++) { my $var = "KPI$i"; no strict 'refs'; print "line", $$var, "\n"; }
    But I can't imagine why you want it this way. Use an array or a hash:
    use strict; use warnings; my @KPI = (10, 20, 30, 40, 50); for (my $i = 0; $i < @KPI; $i++) { print "line", $KPI[$i], "\n"; }
Re: how can print the variable values
by linuxer (Curate) on Dec 01, 2008 at 12:41 UTC

    Why do you want to stick to symbolic references?

    What's the problem using a hash or an array?

Re: how can print the variable values
by dharanivasan (Scribe) on Dec 01, 2008 at 13:26 UTC
    Better you can use array.
    use strict; use warnings; our $KPI0=10; our $KPI1=20; our $KPI2=30; our $KPI3=40; our $KPI4=50; print ${$main::{"KPI$_"}}."\n" foreach(0..4);