You must be the same person who posted
create subroutine. You
really should show us what your requirements are, and most
importantly, what you data looks like. Let's make some up.
Save this in a text file named
in_file.txt:
D:Aspartic Acid
E:Glutamic Acid
F:Phenylalanine
G:Glycine
H:Histidine
I:Isoleucine
K:Lysine
L:Leucine
M:Methionine
N:Asparagine
Our requirements will be simple:
- pass a file name ('in_file.txt') to a subroutine that
- opens the file in read mode
- reads one line at a time
- remove trailing newline
- splits the line on a token (':') into two elements
- the first element is a key
- the second element will be the value
- stores the key-value pair in a hash
- returns the hash
- store the returned hash in a new hash
- loop through the hash and print the key-val pairs
Here goes:
#!/usr/bin/perl -w
# always use strict and warnings (-w from above)
use strict;
# 1 and 2
my %new_hash = create_hash('in_file.txt');
# 3
while(my($key,$val) = each %new_hash) {
print "$key => $val\n";
}
sub create_hash {
my $filename = shift;
my %hash;
# 1.1
open(FILE,'<',$filename) or die "can't read $filename: $!";
# 1.2 - you get the point ;)
while (my $line = <FILE>) {
chomp $line;
my($key,$val) = split (':',$line,2);
$hash{$key} = $val;
}
return %hash;
}
Now, at thist point i recommend you go buy and read
Learning Perl. After you get some
basics under your belt, you can then check out
BioPerl and their lengthy
Tutorial.
Good luck!
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.