#!/usr/bin/perl my $file = $ARGV[0]; my $new_length = $ARGV[1]; open (DAT, $file) || die "couldn't open the file!"; my $raw_data = ''; while (){ chop; $raw_data .= $_; } my @array = split(/%/, $raw_data); #array holds whole text file foreach(@array){ $i = 0; @small_array = {}; $prev_end_of_line = 0; #read the current paragraph into an new array @small_array = split(//,$_); foreach(@small_array){ #option 1: space found at standard position if(($small_array[$prev_end_of_line+$new_length] =~ /\s/)&&$found!=1){ $prev_end_of_line = $prev_end_of_line+$new_length; $found = 1; } elsif($found!=1){ #start backtracking for($j=($prev_end_of_line+$new_length)-1; ;$j--){ #option 3: no space found if($j==$i&&$i>0){ $prev_end_of_line = $prev_end_of_line+$new_length; $found = 1; last; } #option 2: space found at position $j if($small_array[$j] =~ /\s/){ $prev_end_of_line = $j; $found = 1; last; } } } print $_; $i++; if($i eq $prev_end_of_line){ print "\n"; $found = 0; } } print "\n%\n"; $found = 0; }