CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [Laurent_R] just starting out, comparing two arrays: Edit Log



hwnd
User

Jun 24, 2013, 9:43 PM


Views: 541
Re: [Laurent_R] just starting out, comparing two arrays

A few options you can do here, following what the other OPS have said. Storing in a hash.

Example '/etc/passwd'


Code
root:x:0:0:root:/root:/bin/bash  
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin



Example '/etc/group'


Code
root:x:0:root  
bin:x:1:root,bin,daemon
daemon:x:2:root,bin,daemon
adm:x:4:root,adm,daemon



The long way doing this:


Code
use strict;  
use warnings; # always use for catching errors early.

my %users; # define empty hash %users
my %group; # define empty hash %group

open my $fh1, '<', '/etc/passwd' or die "failed open $!";
while (<$fh1>) {
my $id = (split /:/)[0]; # split the fields, [0] is the first field before the colon.
$users{$id} = 1; # build %users hash with $id as key and value as 1
}
close $fh1;

open my $fh2, '<', '/etc/group' or die "failed open $!";
while (<$fh2>) {
my $id = (split /:/)[0]; # split the fields, [0] is the first field before the colon.
$group{$id} = 1; # build %group hash with $id as key and value as 1
}
close $fh2;

for ( keys %group ) { # iterate over %group hash keys
print "$_\n" unless $users{$_}; # print the extra that dont match both hashes
}



An easier way:


Code
Using map here. map runs an expression on each list element and returns list results.   
Were defining hash %users and %group to map the first field of the file with split and
make that field our hash key and give it the value of 1. Then we are using @results array
to use map to check if the %users key exists in %group and finally iterate through @results
and print the users found that were different.

open my $fh1, '<', '/etc/passwd' or die "failed open $!";
open my $fh2, '<', '/etc/group' or die "failed open $!";

my %users = map { (split /:/)[0] => 1 } <$fh1>;
my %group = map { (split /:/)[0] => 1 } <$fh2>;
close $fh1;
close $fh2;

my @results = map { $users{$_} ? () : $_ } keys %group;

foreach (@results) {
print "'$_' found in group\n";
}



(This post was edited by hwnd on Jun 24, 2013, 9:48 PM)


Edit Log:
Post edited by hwnd (User) on Jun 24, 2013, 9:48 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives