0

異なるドメインからの異なる電子メール ID を含むファイルから読み取る Perl プログラム。そして、ドメイン部分を削除してユーザー名をリストします。

例:

入力ファイルには次が含まれます。

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); 
4

3 に答える 3

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のおかげで、現在も将来も問題を解決できます。

于 2013-05-17T04:00:07.817 に答える
0

コードに間違いがいくつかあります。

  1. @として文字列内をエスケープする必要があります\@
  2. Perl 配列を定義するには、 を使用します@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より明確にする代わりに使用$_する、追加の配列を作成するのではなく、分割の結果をすぐに変数に保存するなど、いくつかのことを単純化しました。

于 2013-05-17T03:53:02.323 に答える
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);

ハッシュ内のすべてのドメインと、配列参照である値としてのユーザー名があります。反復するか、ダンパーを使用できます

于 2013-05-17T13:09:36.590 に答える