From 8d69307cd82a6e996e93f2b03a61961496d8e68f Mon Sep 17 00:00:00 2001 From: Maxime Demolin Date: Fri, 17 Feb 2012 20:38:17 +0100 Subject: [PATCH] in fact, I *really* prefer re --- S2/Programmation/TD3/concordancer.pl | 52 ++++++++-------------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/S2/Programmation/TD3/concordancer.pl b/S2/Programmation/TD3/concordancer.pl index 6a50a95..bbd7dcf 100755 --- a/S2/Programmation/TD3/concordancer.pl +++ b/S2/Programmation/TD3/concordancer.pl @@ -72,52 +72,30 @@ sub concordancer { # read it while (my $line = ) { - # look where the word starts in the line - my $start_pos = index($line,$word_to_look_for); - - # if word was not found, index = -1 - # so we check it was somewhere in the line - if ($start_pos != -1) { - # we compute where we should start to extract from the left - # and where it ends - my $left_start = $start_pos - $side_spread; - my $left_end = $side_spread; - - # in case the starting position is inferior to the context length - # we must ensure we won't get a negative number - if ($start_pos < $side_spread) { - $left_start = 0; - $left_end = $start_pos; - } - - my $left_context = substr($line,$left_start,$left_end); - - # and same thing with the rigth context - my $right_start = $start_pos + length($word_to_look_for); - - my $right_context = substr($line,$right_start,$side_spread); + while ($line =~ m/ + (?.{0,$side_spread}) # match the left part + $word_to_look_for # match the word + (?.{0,$side_spread}) # match the right part + /mgx) { - # we chomp it in case it reached end of line - # and included the trailing line - chomp($right_context); + # results are stored in a hash + my %concord = ( + left => $+{left}, + right => $+{right} + ); # now we have everything, # fill with white spaces to get a pretty aligned output - if (length($left_context) < $side_spread) { - my $left_missing = $side_spread - length($left_context) ; - $left_context = " " x $left_missing . $left_context; + if (length($concord{left}) < $side_spread) { + my $left_missing = $side_spread - length($concord{left}) ; + $concord{left} = " " x $left_missing . $concord{left}; } - # results are stored in a hash - my %concord = ( - left => $left_context, - right => $right_context - ); - # and this hash is added to the results push @results, { %concord }; } - } + + } close(INPUT);