By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,710 Members | 1,970 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,710 IT Pros & Developers. It's quick & easy.

Perl functions: subroutines

P: 2
Hi all, my first time here! Can someone assist me? i need to write a "simple" perl scripts to cancatenate two strings (preferably short DNA sequences) using the subroutine function? Mine doesnt print anything.Also need general hints on subroutines.I'm still new to perl (and programming in general!).

Here is the script I had writen:
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl;
  2. #subroutine to concatenate two strings of dna
  3. #practicesubroutines1.txt
  4.  
  5. sub conc($);
  6. print "enter the dna sequence1>>";
  7. $dna1=<>;
  8. print "enter dna sequence2>>";
  9. $dna2=<>;
  10. $newdna=conc($dna);
  11. print "the new dna is $newdna\n";
  12.  
  13. sub conc($)
  14. {
  15. my $dna1=$_[0];
  16. my $dna2=$_[0];
  17. $dna="$dna1"."$dna2";
  18. return $dna;
  19. }
  20.  
Mar 8 '10 #1
Share this Question
Share on Google+
4 Replies


jkmyoung
Expert 100+
P: 2,057
Are you using <STDIN> ? eg
$dna1=<STDIN>;

Your function call has to pass both sequences in, eg:
Expand|Select|Wrap|Line Numbers
  1. $newdna=conc($dna1, $dna2);
  2. ....
  3. sub conc{
  4. $str = ""
  5. foreach (@_) { $str = $str . $1;}
  6. return $str;
  7. }
  8.  
Mar 8 '10 #2

Expert Mod 100+
P: 589
jkmyoung,

Where did you get that $1 var? Did you mean to use $_?
Mar 8 '10 #3

Expert Mod 100+
P: 589
Lets use a version that doesn't take unnecessary steps and is warnings and strict safe.

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl;
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. print "enter the dna sequence1>>";
  7. chomp(my $dna1 = <>);
  8.  
  9. print "enter dna sequence2>>";
  10. chomp(my $dna2 = <>);
  11.  
  12. my $newdna = conc($dna1, $dna2);
  13. print "the new dna is $newdna\n";
  14.  
  15. sub conc {
  16.     return join('', @_);
  17. }
Mar 8 '10 #4

P: 6
Little modification to your code

Expand|Select|Wrap|Line Numbers
  1. # #!/usr/bin/perl;
  2. # #subroutine to concatenate two strings of dna
  3. # #practicesubroutines1.txt
  4.  
  5.  sub conc($$);
  6.  print "enter the dna sequence1>>";
  7.  $dna1=<>;
  8. chomp($dna1);
  9.  print "enter dna sequence2>>";
  10.  $dna2=<>;
  11. chomp($dna2);
  12.  $newdna=conc($dna1,$dna2);
  13. print "the new dna is $newdna\n";
  14.  
  15.  sub conc($$)
  16.  {
  17.  my $dna1=$_[0];
  18.  my $dna2=$_[1];
  19.  $dna="$dna1"."$dna2";
  20.  return $dna;
  21.  }
Mar 26 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.