Perl functions: subroutines

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Wilbur
    New Member
    • Mar 2010
    • 2

    Perl functions: subroutines

    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:
    Code:
    #!/usr/bin/perl;
    #subroutine to concatenate two strings of dna
    #practicesubroutines1.txt
    
    sub conc($);
    print "enter the dna sequence1>>";
    $dna1=<>;
    print "enter dna sequence2>>";
    $dna2=<>;
    $newdna=conc($dna);
    print "the new dna is $newdna\n";
    
    sub conc($)
    {
    my $dna1=$_[0];
    my $dna2=$_[0];
    $dna="$dna1"."$dna2";
    return $dna;
    }
    Last edited by numberwhun; Mar 8 '10, 05:41 PM. Reason: Please use code tags!!!
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Are you using <STDIN> ? eg
    $dna1=<STDIN>;

    Your function call has to pass both sequences in, eg:
    Code:
    $newdna=conc($dna1, $dna2);
    ....
    sub conc{
    $str = ""
    foreach (@_) { $str = $str . $1;}
    return $str;
    }

    Comment

    • RonB
      Recognized Expert Contributor
      • Jun 2009
      • 589

      #3
      jkmyoung,

      Where did you get that $1 var? Did you mean to use $_?

      Comment

      • RonB
        Recognized Expert Contributor
        • Jun 2009
        • 589

        #4
        Lets use a version that doesn't take unnecessary steps and is warnings and strict safe.

        Code:
        #!/usr/bin/perl;
        
        use strict;
        use warnings;
         
        print "enter the dna sequence1>>";
        chomp(my $dna1 = <>);
        
        print "enter dna sequence2>>";
        chomp(my $dna2 = <>);
        
        my $newdna = conc($dna1, $dna2);
        print "the new dna is $newdna\n";
         
        sub conc {
            return join('', @_);
        }

        Comment

        • Chendil
          New Member
          • Mar 2010
          • 6

          #5
          Little modification to your code

          Code:
          # #!/usr/bin/perl;
          # #subroutine to concatenate two strings of dna
          # #practicesubroutines1.txt
          
           sub conc($$);
           print "enter the dna sequence1>>";
           $dna1=<>;
          chomp($dna1);
           print "enter dna sequence2>>";
           $dna2=<>;
          chomp($dna2);
           $newdna=conc($dna1,$dna2);
          print "the new dna is $newdna\n";
          
           sub conc($$)
           {
           my $dna1=$_[0];
           my $dna2=$_[1];
           $dna="$dna1"."$dna2";
           return $dna;
           }

          Comment

          Working...