Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks
I'm having dificulty with hashes. I'm trying to write a script that will take two lists and return strings of random combinations of their elements ie A1 {foo1, foo2, foo3, foo4...} and A2 {bar1, bar2, bar3, bar4...} to give:
I need the strings to be unique so I decided to put them into a hash setting the string as the key. The code I've written works to a point. I get a hash of unique strings, but not always to the number I specify, ie $size=100, keys(%ligands) = 993. I'm guessing this is becuase some of the values were non-unique.
Is there a way I can use $size to set the size of the hash and keep adding strings till I get to the limit?
I've attached my current code for your ammusement. I'm quite new to programming and Perl so please be gentle, it my not be the most elegant ever written!
Thanks for you help
Hassan
The code
#!/usr/bin/perl # Test code for hash use Data::Random qw(:all); use List::Util qw(shuffle); # Read in two files containing Rgroups into 2 arrays unless ( open (A1_FILE, "A1.txt")) { print "Cannot find A1 list\n\n"; exit } unless ( open (A2_FILE, "A2.txt")) { print "Cannot find A2 list \n\n"; exit } my @A1 = <A1_FILE>; chomp (@A1); close (A1_FILE); my @A2 = <A2_FILE>; chomp (@A2); close (A2_FILE); my @A1_shuffled = shuffle (@A1); my @A2_shuffled = shuffle (@A2); print "\nEnter the name of the output file(give full path): "; my $outfile = <STDIN>; chomp $outfile; open (OUTPUT, ">$outfile"); print "\nEnter the number of ligands needed: "; my $size = <STDIN>; chomp $size; print "\nEnter the scaffold name: "; my $scaffold = <STDIN>; chomp $scaffold; my %ligands = (); for ($i=0; $i<$size; $i++) { my @random_A1 = rand_set( set => \@A1_shuffled, size => 1 ); my @random_A2 = rand_set( set => \@A2_shuffled, size => 1); $ligands{$ligand}=$i; } my $keys = keys(%ligands); my @temp = keys(%ligands); for ($z=0; $z<$keys; $z++){ print OUTPUT @temp[$z]; print OUTPUT "\n"; } close OUTPUT; print "\n"; print "\nSize of hash: ". keys(%ligands) . ".\n"; exit
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Filling hashes
by davorg (Chancellor) on May 10, 2006 at 15:31 UTC | |
|
Re: Filling hashes
by japhy (Canon) on May 10, 2006 at 15:28 UTC | |
|
Re: Filling hashes
by Hue-Bond (Priest) on May 10, 2006 at 15:28 UTC | |
|
Re: Filling hashes
by leocharre (Priest) on May 10, 2006 at 17:35 UTC |