There are a bunch of things that can be improved in your script. The solution to your immediate problem is to have the sub return the result string instead of printing it. But not too:

  1. Don't use $a and $b as general purpose variables - they are special (used by sort). In fact always use sensible names, they help understanding a script much more than comments or additional documentation.
  2. Always use strictures (use strict; use warnings;). Note that use warnings; is better than including the -w flag on the command line.
  3. Use sensible indentation!
  4. Use three parameter open and lexical file handles.
  5. Avoid the C style for loop. Use a Perl style for loop instead. Not though that I've used a while loop and changed the way substr works instead.
#!/usr/bin/perl use strict; use warnings; my $output = "Fmd.txt"; my $seq = "BATCATEATFATRAT"; my $result = splitSequence($seq, 3); print "\nResult:\n$result\n"; open my $outFile, '>', $output or die qq{Cannot open file "$output": $ +!.\n}; print $outFile "Formatted Data:\n$result\n\n"; close $outFile; sub splitSequence { my ($sequence, $length) = @_; my $result; while (length $sequence) { $result .= substr($sequence, 0, $length, '') . "\n"; } return $result; }

Prints:

Result: BAT CAT EAT FAT RAT
True laziness is hard work

In reply to Re: Is it possible to write the results of a subroutine for data formatting to a text file? by GrandFather
in thread Is it possible to write the results of a subroutine for data formatting to a text file? by supriyoch_2008

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.