Bijgom has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I am new to perl and to this forum...

I would hihly appreciate if anyone could help with the problem I encountered:

In the following script (matching a string +peptide sequence+ to a protein sequence), why at the end when I print the results I cannot see which string (peptide) matches which protein sequence. In practice, when I do: print "found '$peptide' in $test_prot_id\n"; it says : "found '' in blala" (so $peptide remain blank) in other words it reports the protein sequence ID but not the matching string. Thank you in advanvce for your help,

while(<MYFILE2>) { chomp ($_); push(@peptide, $_); #adds each line to an array print "peptides: @peptide\n"; foreach my $test_prot_id (keys %proteins) { my $test_prot_seq = $proteins{$test_prot_id}; if ($test_prot_seq =~/($peptide)/) { print "found $peptide in $test_prot_id\n"; $results{$test_prot_id} ++; } } }

Replies are listed 'Best First'.
Re: matching &printing S variable of an array
by CountZero (Bishop) on Feb 23, 2015 at 17:28 UTC
    $peptide remains blank because it is never initialized.

    To avoid such errors, always start your scripts with use strict; use warnings;

    Add

    my $peptide = $_;
    before the start of your foreach loop and see if that helps.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re: matching &printing S variable of an array
by toolic (Bishop) on Feb 23, 2015 at 16:46 UTC
    • Read Writeup Formatting Tips and edit your post, adding "code" tags around your code.
    • Show a small sample of your input file in "code" tags.
    • Show a little of what is in the %proteins hash. Read http://sscce.org
Re: matching &printing S variable of an array
by FreeBeerReekingMonk (Deacon) on Feb 23, 2015 at 18:36 UTC
    Like CountZero already pointed out:
    chomp(); # remove the newline from $_; $peptide = $_; # Current peptide (line) being checked push(@peptides, $peptide); # Adds each peptide to an array (note the s +ingular/plural)
    The thing is, if you want the last element of an array, you need to do: $peptide = $peptides[$#peptides]

    Alternatively, you can write both assignments in a single line:

    push(@peptides, $peptide = $_);
      Cheers guys! The solution consisting in initializing $peptide while populating my array works best for me : push(@peptides, $peptide = $_); Thanks a lot for your kind help. Best,