I have come to seek the wisdom of the Perl
I'm working on a little project of mine (i'm a biologist, as you will notice :P). I'm trying to read through a pre-formatted text file, locate specific words and replace them, then print the changed lines.
Here's what I came up with:
@gi=("Galpha-i1", "Galpha-i2", "Galpha-i3"); @gt=("Galpha-t1", "Galpha-t2", "Galpha-t3"); %gp = ( 'G11' => 'Galpha-11', 'G12' => 'Galpha-12', 'G13' => 'Galpha-13', 'G14' => 'Galpha-14', 'G15' => 'Galpha-15', 'G16' => 'Galpha-16', 'Gs' => 'Galpha-s', 'Gz' => 'Galpha-z', 'Golf' => 'Galpha-olf', 'Go' => 'Galpha-o', 'Gq' => 'Galpha-q', 'Gi' => "@gi", 'Gt'=> "@gt",) ; #the program is about g-proteins.the keys of the hash are the words i #want to find and the values the words i'd like to replace them with while (<>) { #while loop to go through the file and the pattern matching to get the #correct tab if ($_=~/^.*\t.*\t(.*)\t.*\t.*/mgi) { $i=$1; $f=$_; chomp $f; $i=~s/ //g; $j=$gp{$i}; @values= split (' ',$j); foreach $val (@values) { $k=$f; $k=~s/$i/$val/mg; print "$k\n"; } } }
This works perfectly if i'm not gravely mistaken, yet it seems rather unorthodox. I mean, i'm creating a table (eg @gi)which is read in the hash as a scalar and i split it again to get a new table, so i can get all the different outputs. If i use Gi=>@gi , without "", then i only get the gi[0] instead of the whole @gi table. Any ideas how to improve on this code?
UPDATE:Thank you for your responses.
You are right of course about the data. As hbm guessed it looks like this:
RandomID Name Gi TissueI read all about references before writing the original code but as i was pretty inexperienced in using them, i did away with them.
++wsfp, what you suggested was actually my first try (trying to figure out if my variable was an array or scalar) but i had no idea how to do hat, hence the work-around :)
++hbm, sorry about the modifiers, old habits you see :P
I'll give it a run and let you know how it turns out. Thank you Yet another UPDATE:
++Util the uniformity helped me better understand the whole code
++Marshall the interpretation is correct :) And the tips have proven very helpful indeed. Also i found the "next if" statement very interesting and i'll start implementing something like that more often in my progams
Thank you all
In reply to How to improve my code? main concern:array as hash element by xargon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |