Perl程序从包含来自不同域的不同电子邮件ID的文件中读取。并通过删除域部分列出用户名。
示例:
输入文件将包含:
abc@gmail.com
xyz@yahoo.com
pqr@test.com
输出文件应如下所示:
The domain gmail.com contains following userid:
abc
The domain yahoo.com contains following userid:
xyz
The domain test.com contains following userid:
pqr
我尝试使用代码,但它只是分隔域名和用户名,但没有根据域名列出用户名。
use strict;
print "Enter the file name where emailids of different domains are present\n";
my $file=<stdin>;
open(DATA, "$file") or die ("Could not open the file\n");
while(<DATA>){
my @field=split(/@/, "$_" );
chomp $_;
my $username=@field[0];
my $domain=@field[1];
print "The user id is $username \nThe domain name is $domain \n";
}
close (DATA);
答案 0 :(得分:1)
为了保持这一点,您希望在找到地址时填充数组的散列而不是打印:
my %domains;
while(<DATA>){
my @field=split(/@/, "$_" );
chomp $_;
my $username=$field[0];
my $domain=$field[1];
#print "The user id is $username \nThe domain name is $domain \n";
push @{$domains{$domain}}, $username;
}
close (DATA);
for my $domain (sort keys %domains) {
print "The domain gmail.com contains following userid:\n";
print "$_\n" for sort @{$domains{$domain}};
}
沉溺于这是我怎么做的:
#! /usr/bin/env perl
use common::sense;
use Email::Address;
use YAML 'Dump';
die "usage: $0 <file1> [<file2> ... <fileN>]\n" unless @ARGV;
# although <> reads STDIN in the absense of @ARGV,
# which is often what you want.
my %hosts;
while (<>) {
for (Email::Address->parse($_)) {
push @{$hosts{$_->host}}, $_->user
}
}
print Dump \%hosts;
给定一个名为'file'的文件,其中包含:
abc @gamil.com
abd @gamil.com
abe @gamil.com
xyz@yahoo.com
xy1@yahoo.com
xy2@yahoo.com
pqr@test.com
pqs@test.com
pqt@test.com
这是用法和输出:
$ perl test
usage: test <file1> [<file2> ... <fileN>]
$ perl test file
---
gamil.com:
- abc
- abd
- abe
test.com:
- pqr
- pqs
- pqt
yahoo.com:
- xyz
- xy1
- xy2
YAML可读且有用。 Email::Address现在和将来都会给我们带来麻烦。
答案 1 :(得分:0)
您的代码中几乎没有错误:
@
内部字符串转义为\@
。@array
。但要解决数组中的元素,您需要使用$
:$array[0]
。这意味着,您的代码应如下所示:
use strict;
print "Enter the file name where emailids of different domains are present\n";
my $file=<stdin>;
open DATA, "$file" or die $!;
while (my $line = <DATA>) {
chomp $line;
my ($username, $domain) = split /\@/, $line;
print "The user id is $username \nThe domain name is $domain \n";
}
close DATA;
我简化了一些事情,例如使用$line
代替$_
来使其更清晰,并立即将分割结果保存到变量中,而不是创建额外的数组。
答案 2 :(得分:0)
试试这个
my $file=<stdin>;
my %hash;
open(DATA, "$file") or die ("Could not open the file\n");
while(<DATA>){
chomp($_);
my @field=split(/\@/, "$_" );
chomp(@fields);
push(@{$hash{$field[1]}},@field);
}
close (DATA);
您拥有散列中的所有域及其用户名作为数组引用的值。你可以迭代它或使用Dumper