#!/usr/bin/perl while ( <> ) { $fn = 1 if /^\@footnote:/; if ( $fn ) { ( s/^\[(\d+)\] (.*)// ) && ( $footer->{ $fn_hash->{ $1 } } = sprintf "%s", $2 ) || print; } else { while ( s/^(.*?)\[(\d+)\]//x ) { printf "%s[%s]", $1, $fn_hash->{ $2 } ||= ++$index; } print; } } foreach ( sort keys %$footer ) { printf "[%s] %s\n", $_, $footer->{ $_ }; }