debugMinor
Perl code that breaks a line after fixed number of columns
Viewed 0 times
afternumberlineperlcolumnsfixedthatcodebreaks
Problem
Here is a simple program that I created to print a file by breaking it after a fixed number of columns. I feel it can be optimized but not sure how. Any feedback is great.
#This is a simple program that takes a file and the limits the columns length to
#the number passed in as second argument
if ($#ARGV \n", $0);
exit(-1);
}
$file=$ARGV[0];
open(INFO, $file) or die("Could not open file.");
$LINE_LENGTH = $ARGV[1];
$count = 0;
foreach $line () {
#print $line;
if (length($line) = $LINE_LENGTH) {
$cur_str = substr($remaining_line, 0, $LINE_LENGTH - 1 );
printf("%s\n", $cur_str );
$remaining_line = substr($remaining_line, $LINE_LENGTH - 1);
$remaining_chars = $remaining_chars - length($cur_str);
}
printf("%s",$remaining_line );
}
if ($++counter == 2){
last;
}
}
printf("\n");
close(INFO);Solution
I am not sure it can be optimized in a sense of better performance. It could be streamlined though. The initial test for
PS: I am not familiar with perl enough. If there is a
length($line) <= $LINE_LENGTH is just redundant. Compare:while (length ($line) > LINE_LENGTH) {
$prefix = substr($line, 0, $LINE_LENGTH - 1 );
$line = substr($line, $LINE_LENGTH - 1);
printf("%s\n", $prefix);
}
printf("%s",$line );PS: I am not familiar with perl enough. If there is a
split at position function, you may use it instead of calling substr twice.Code Snippets
while (length ($line) > LINE_LENGTH) {
$prefix = substr($line, 0, $LINE_LENGTH - 1 );
$line = substr($line, $LINE_LENGTH - 1);
printf("%s\n", $prefix);
}
printf("%s",$line );Context
StackExchange Code Review Q#107580, answer score: 4
Revisions (0)
No revisions yet.