需要帮助解析从ldap到csv的结果

时间:2009-05-28 17:23:36

标签: perl csv loops ldap flow-control

我正在尝试创建一个脚本来生成一个csv文件,其中包含一些使用Net :: LDAP的ldap查询的结果,但是如果@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,,

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

1 个答案:

答案 0 :(得分:2)

标记您的while循环:

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

并使用:

next Record;

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

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