$str =~ s[(bar.+?qux)|(qux.+?bar)|(foo)][defined $3 ? '123' : (defined($2) ? $2 : $1)]ge;