in reply to File Iteration and looking for specific matching data

G'day bshah,

"Open user.txt and iterate through each user and check each line on ldap.txt in dn: line."

That would mean you'd be reading your multi-gigabyte ldap.txt multiple times (i.e. once for every user in user.txt). Instead, read user.txt once and create a regex with a capture group containing an alternation of all the users. If that's unfamiliar to you, see "Perl regular expressions tutorial".

"If matches, then store the value of all the lines matching maillocaladdress to the varialbe , I assume in hash key/value pari but here the values are more than one."

What you want here is a "hash of arrays".

Putting all that together (based on your sample data):

#!/usr/bin/env perl use strict; use warnings; use autodie; my ($user_file, $ldap_file) = qw{pm_1079590_user.txt pm_1079590_ldap.t +xt}; open my $user_fh, '<', $user_file; my @users; while (<$user_fh>) { chomp; push @users, $_; } close $user_fh; my $user_re = 'uid=(' . join('|', @users) . '),'; my %user_ldap_data; open my $ldap_fh, '<', $ldap_file; my $user = ''; while (<$ldap_fh>) { if (/^dn:/) { $user = /$user_re/ ? $1 : ''; next; } next unless $user; push @{$user_ldap_data{$user}}, $1 if /^maillocaladdress:\s+(\S+)/ +; } close $ldap_fh; use Data::Dump; dd \%user_ldap_data;

Output:

{ game => [ "game\@example.com", "game.test\@example.com", "game-test\@example.com", ], test1 => [ "test1\@example.com", "test.team\@example.com", "test11\@example.com", ], }

-- Ken

Replies are listed 'Best First'.
Re^2: File Iteration and looking for specific matching data
by bshah (Novice) on Mar 26, 2014 at 02:07 UTC

    Thank you Ken

    Do you mind explaining the following piece of code please ?
    'uid=(' . join('|', @users) . '),'; $user = /$user_re/ ? $1 : ''

    Kind Regards
      "Do you mind explaining the following piece of code please ?"

      Well, you've listed two pieces of code which appear in different parts of the script I posted:

      "'uid=(' . join('|', @users) . '),';"

      I've already provided a link to what's going on here: "... create a regex with a capture group containing an alternation of all the users. If that's unfamiliar to you, see "Perl regular expressions tutorial".". Was there something in that documentation that you didn't understand?

      See "Perl functions A-Z" for information about join (or any of the other core functions I've used).

      You could always run the code I provided with a print statement to see how that expression is evaluated.

      "$user = /$user_re/ ? $1 : ''"

      That's the ternary (aka conditional) operator: see "perlop: Conditional Operator".

      -- Ken

        Thank you Ken for all your help. Greatly appreciate it.