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:
coping shared disks to array...

 



zohman
Novice

Dec 28, 2016, 6:05 AM

Post #1 of 5 (2277 views)
coping shared disks to array... Can't Post

Hi,

I've a scenario where i need to get only disks that are shared among all servers,
for example:

srv1:disk1,disk2,disk3,disk4
srv2:disk1,disk4,disk200,disk400
srv3:disk1,disk3,disk4,disk500,disk740
srv58:disk1,disk3,disk4,disk124,disk142
...

my desired result would be ARRAY that contain:
disk1 and disk4 which shared between all listed servers as you can see.

what is the best method?

Thanks!


Laurent_R
Veteran / Moderator

Dec 28, 2016, 9:49 AM

Post #2 of 5 (2268 views)
Re: [zohman] coping shared disks to array... [In reply to] Can't Post

Use a hash to store the disks as keys and the list of servers (or, simpler, a counter of servers) as value.

At the end, traverse the hash and keep the disks which have all servers (or a count of all servers) in the hash.


zohman
Novice

Dec 31, 2016, 12:12 PM

Post #3 of 5 (2208 views)
Re: [Laurent_R] coping shared disks to array... [In reply to] Can't Post

i don't understand your method, anyway i came out with this:


Code
 

my %hash = (
'srv1' => {
'disk1' => 1,
'disk2' => 1,
'disk3' => 1,
'disk4' => 1
},
'srv2' => {
'disk1' => 1,
'disk4' => 1,
'disk200' => 1,
'disk400' => 1
},
'srv3' => {
'disk1' => 1,
'disk3' => 1,
'disk4' => 1,
'disk500' => 1,
'disk740' => 1
},
'srv58' => {
'disk1' => 1,
'disk3' => 1,
'disk4' => 1,
'disk124' => 1,
'disk142' => 1
}
);

my $key_count = scalar keys %hash;

my %seen;
foreach my $xval (values %hash) {
$seen{$_}++ for keys %{$xval};
}

my @shared;
foreach (keys %seen) {
push @shared,$_ if $seen{$_} == $key_count;
}



can't tell if this is the right way.. but it's get the job done,
i count how much servers i've and i need same disk shared across all
so i count them as well, and push to the array if it match.

Regards,
Zohman.


BillKSmith
Veteran

Jan 1, 2017, 2:35 PM

Post #4 of 5 (2180 views)
Re: [zohman] coping shared disks to array... [In reply to] Can't Post

This is exactly what Laurent suggested. The function grep is intended to be a filter. I would consider it good practice to use it here.

Code
my @shared = grep {$seen{$_} == $key_count} keys %seen; 

$" = "\n";
print "@shared\n";

Good Luck,
Bill


zohman
Novice

Jan 3, 2017, 10:17 AM

Post #5 of 5 (2138 views)
Re: [BillKSmith] coping shared disks to array... [In reply to] Can't Post

what is our motto?
"There's more than one way to do it" :-)

like it, thanks.

 
 


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

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