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:
- 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.
- Always use strictures (use strict; use warnings;). Note that use warnings; is better than including the -w flag on the command line.
- Use sensible indentation!
- Use three parameter open and lexical file handles.
- 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