如何在 perl 中打印迭代字母

  • 本文关键字:迭代 打印 perl perl
  • 更新时间 :
  • 英文 :


我需要一些关于如何打印以获得预期结果的后见之明。如何为我拥有的数据(如i++(自动迭代字母,以及如何重置每个HOMEi值?

预期成果:

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 nn";
foreach my $alphabet(@alphabets)
{
print "$alphabet)";
foreach my  $home(@homes) 
{
foreach my $location(@location)
{
foreach my $residence (@residences)
{
if ($home=~ /^residence(.*)/)
{
print "thomet";
print $i++,")$1n";     
}
}
print "t $locationn"; 
}
}

新脚本

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

我得到的结果

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 

不是$alphabet,而是像使用$i一样初始化它,但使用a。Perls++操作员知道如何处理字母:

my $alphabet = 'a';
...
$alphabet++;

不要$i为事实上的全局变量,而是将其声明为比您希望重置的位置高一个循环级别:

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

参见

自动递增时的 perlop

最新更新