likbez has asked for the wisdom of the Perl Monks concerning the following question:
NOTES:
For example, in the example below, I want to replace fragment between markers AAAAAA and BBBBBB with the list ( 'f11','f12','f13') and the fragment between markers CCCCCC and DDDDDD with the list ("f21","f22").
aaa aaa AAAAAA ccc ddd BBBBBB 111 222 333 CCCCCC 444 555 666 DDDDDD 777 888 999Thanks in advance for any help.
Again I am talking here not about the run of the mill solution (have three parallel arrays, for example, startmarker and stopmarker with markers and two dimensional (array of lists) replacement_list with the replacement fragments, find first starting marker in the file, loop till the end marker, inject the corresponding replacement fragment into output stream via the inner loop, and so on), but about the best, most elegant, way to accomplish this task in Perl that fully utilizes capabilities of the language.
May be it is possible to adapt range operator to the task:
0] # cat test_range while( $text=<DATA> ){ print "$. $text"; if ( ($text=~/^AAAAAA/) .. ($text=~/^BBBBBB/ ) ){ if ($text=~/^AAAAA/){ print "========= Start of the fragment detected at $.\n"; } print "Still true at $.\n"; $end=$.; # Is this the only way to detect the end of the fragment +? } } print "========= End of the fragment detected at $end.\n"; __DATA__ aaa aaa AAAAAA ccc ddd BBBBBB 111 222 333 CCCCCC 444 555 666 DDDDDD 777 888 999
Which does allow to detect the start and end of the fragment and can be generalized to use multiple passes over the text to detect all fragments, but I am not sure that this is the optimal way. While this might serve as the base of the shortest solution to the problem, it is impossible to avoid multiple passes over the text.
[0] # perl test_range 1 aaa 2 aaa 3 AAAAAA ========= Start of the fragment detected at 3 Still true at 3 4 ccc Still true at 4 5 ddd Still true at 5 6 BBBBBB Still true at 6 7 111 8 222 9 333 10 CCCCCC 11 444 12 555 13 666 14 DDDDDD 15 777 16 888 17 999 ========= End of the fragment detected at 6.
I have only a very basic knowledge of this operator.
|
|---|