in reply to Is it possible to write the results of a subroutine for data formatting to a text file?

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
  • Comment on Re: Is it possible to write the results of a subroutine for data formatting to a text file?
  • Select or Download Code