如何在Perl中打印迭代字母

时间:2018-10-01 06:31:08

标签: perl

我需要一些后见之明,如何打印才能获得预期的结果。如何仅对我拥有的数据(如i)自动进行字母迭代,以及如何重置{{ 1}}中的每个HOME

预期结果:

RESIDENCE LIST
a) HOME 1   1. Albert Einstein
            2. Adriana
            3. Anna
   LOCATION USA
b) HOME 2   1. Blaine Pascal
            2. Caroline Herschel
            3. Cecilia Payne-Gaposchkin
   LOCATION GERMANY
c) HOME 3   1. Dorothy Hodgkin
            2. Edmond Halley
            3. Edwin Powell Hubble
   LOCATION INDIA 

use strict;
use warnings;

my i=1;
my @alphabets=("a".."z");
my @homes=qw(
HOME1
HOME2
HOME3
);
my @residences=qw(
HOME1 Albert Einstein
HOME1 Adriana
HOME1 Anna
HOME2 Blaine Pascal
HOME2 Caroline Herschel
HOME2 Cecilia Payne-Gaposchkin
HOME3 Dorothy Hodgkin
HOME3 Edmond Halley
HOME3 Edwin Powell Hubble
);
my @location=qw(
USA
GERMANY
INDIA
);

print  "RESIDENCE LIST \n\n";

foreach my $alphabet(@alphabets)
{
    print "$alphabet)";

    foreach my  $home(@homes) 
    {
        foreach my $location(@location)
        {
            foreach my $residence (@residences)
            {
            if ($home=~ /^residence(.*)/)
            {
            print "\thome\t";
            print $i++,")$1\n";     
            }
            }
        print "\t $location\n"; 
    }

}

新脚本

foreach my  $home(@homes) 
{
   my $i=1;
   foreach my $location(@location)
   {
   foreach my $residence (@residences)
   {
       if ($home=~ /^residence(.*)/)
       {
       print $alphabet++."\n";
       print "\thome\t";
       print $i++,")$1\n";      
       }
       else
       {
       next:
       }
    }

    print "\t $location\n";
    } 
}

我得到的结果

    a) HOME 1   1. Albert Einstein
    b) HOME 1   2. Adriana
    c) HOME 1   3. Anna
    d) LOCATION USA
    e) HOME 2   1. Blaine Pascal
    f) HOME 2   2. Caroline Herschel
    g) HOME 2   3. Cecilia Payne-Gaposchkin
    h) LOCATION GERMANY
    i) HOME 3   1. Dorothy Hodgkin
    j) HOME 3   2. Edmond Halley
    k) HOME 3   3. Edwin Powell Hubble
    l) LOCATION INDIA 

1 个答案:

答案 0 :(得分:1)

与其使用$alphabet进行初始化,而不是使用$i,而是使用a对其进行初始化。 Perls ++运算符知道如何处理字母:

my $alphabet = 'a';

...
    $alphabet++;

与其将$i设置为事实上的全局变量,不如将其声明为要重置的位置的一个循环级别:

...
foreach my $home (@homes) {
    my $i = 1;
    foreach my $location (@location) {
    ...
        $i++
    ....
    };
}

另请参见

perlop on Auto-increment