2

我正在尝试创建一个脚本来使用 Net::LDAP 使用一些 ldap 查询的结果生成一个 csv 文件,但是如果 @attributes 数组的一个元素为空白,我将无法跳过不完整的行。

my @attributes  = ('cn', 'mail', 'telephoneNumber');

因此,例如,如果用户没有列出邮件或没有列出电话号码,那么它应该跳过保留字段而不是返回:

"Foo Bar",, # this line should be skipped since there is no mail nor telephone
"Bar Foo","bar@foo.com", # this line should be skipped too, no number listed
"John Dever","john_dever@google.com","12345657" # this one is fine, has all values

我的循环现在看起来像这样:

# Now dump all found entries
while (my $entry = $mesg->shift_entry()){
    # Retrieve each fields value and print it
    # if attr is multivalued, separate each value
    my $current_line = ""; # prepare fresh line
    foreach my $a (@attributes) {
        if ($entry->exists($a)) {
            my $attr = $entry->get_value($a, 'asref' => 1);
            my @values  = @$attr;
            my $val_str = "";
            if (!$singleval) {
                # retrieve all values and separate them via $mvsep
                foreach my $val (@values) {
                    if ($val eq "") { print "empty"; }
                    $val_str = "$val_str$val$mvsep"; # add all values to field
                }
                $val_str =~ s/\Q$mvsep\E$//; # eat last MV-Separator
            } else {
                $val_str = shift(@values); # user wants only the first value
            }

            $current_line .= $fieldquot.$val_str.$fieldquot; # add field data to current line

        }
        $current_line .= $fieldsep; # close field and add to current line
    }
    $current_line =~ s/\Q$fieldsep\E$//; # eat last $fieldsep
    print "$current_line\n"; # print line
}

我试过这样的代码:

if ($attr == "") { next; }
if (length($attr) == 0) { next; }

和其他几个没有任何运气。我也尝试过简单的 if () { print "isempty"; 调试测试和它不工作。我不确定我该怎么做。

我很感激你能给我的任何帮助或指示我做错了什么。

非常感谢您的帮助。

更新:
每个混乱请求:

my $singleval = 0;

此程序的示例运行将返回:

Jonathan Hill,Johnathan_Hill@example.com,7883                  
John Williams,John_Williams@example.com,3453                     
Template OAP,,                                            
Test Account,,                                                
Template Contracts,,

所以我想做的是跳过所有缺少字段的行,无论是电子邮件还是分机号码。

4

1 回答 1

2

标记你的while循环:

Record: while (my $entry = $mesg->shift_entry()){

并使用:

next Record;

您的问题是您next与您的foreach. 使用标签可以避免这种情况。

顺便说一句,$attr == ''虽然在这种情况下它会起作用,但它的逻辑很糟糕;在 perl 中,==是一个数字比较。字符串比较将是$attr eq ''. 虽然我只是使用next Record unless $attr.

于 2009-05-28T17:28:26.553 回答