my $text = "The cow jumped over the moon"; $text =~ s/(\w+\s+)jumped/$1tripped/; #### if ( $text =~ m/cow\s+(jumped)\s+over/ ) { $1 = "tripped"; } #### if ( $text =~ m/cow\s+(\w+)\s+over/ ) { do_action( $1 ); $1 = calculate_new_action( $1 ); } #### if ( $text =~ m/cow\s+(\w+)\s+over/ ) { do_action( $1 ); my $new_action = calculate_new_action( $1 ); $text =~ s/(cow\s+)(\w+)(\s+over)/$1$new_action$3/; }