消失,我认为我的Perl是生锈:)默认哈希键在Perl
这下面的脚本应该通过包含LDAP记录文本文件的目录遍历特定用户提取特定的信息。如果'productfamily'属性不存在于文件中,我遇到了将'group'散列键从散列引用中删除的问题。
#!/bin/perl
use strict;
use warnings;
use Data::Dumper;
use File::Basename;
sub extract_val {
my $line = shift;
return (split /\:/, $line)[1];
}
my @ldif_files = <tmp/*.ldif>;
my $line_ctr = 0;
my @record_ctr;
for my $ldif_file (@ldif_files) {
open my $fh,'<', $ldif_file or die "Cannot open file: $!";
my @contents = <$fh>;
close $fh;
my $user_record = {
'file' => basename $ldif_file,
'group' => 'BP',
'uid' => '',
'fname' => '',
'lname' => '',
'company' => '',
};
for my $line (@contents){
chomp $line;
$user_record->{'uid'} = extract_val($line) if $line =~ /^uid\:/;
$user_record->{'fname'} = extract_val($line) if $line =~ /^givenname\:/;
$user_record->{'lname'} = extract_val($line) if $line =~ /^sn\:/;
$user_record->{'company'} = extract_val($line) if $line =~ /^o\:/;
$user_record->{'group'} = 'EU' if $line =~ /^productfamily\:/;
}
print Dumper $user_record;
last if $line_ctr++ == 10;
}
输出示例
下面是从输出的两个有代表性的样品。
如果LDAP记录中存在productfamily属性,则显示'group'散列键。
$VAR1 = {
'group' => 'EU',
'uid' => 'abcdef',
'lname' => 'SMITH',
'fname' => 'JOHN',
'file' => 'abcdef.ldif',
'company' => 'Some Company'
};
如果productfamily属性在LDAP记录中不存在,'group'散列键会丢失。
$VAR1 = {
'uid' => 'uvwxyz',
'lname' => 'Bar',
'fname' => 'Foo',
'file' => 'uvwxyz.ldif',
'company' => 'Another Company'
};
Solaris 5.9上的Perl版本为5.8.5。
大约有6000个文件,但我将循环迭代次数限制为10次,因为问题在我的数据文件中出现得早。
尝试单步执行perl调试器中的代码:'perl -d program.pl'。它足够小的代码块,你应该能够在5分钟左右的时间内找出它。 – 2013-04-25 21:53:09