in reply to How do I avoid double substitution when replacing many patterns?

Using an even lesser known regex item...
perl -e ' $f = "\$foo \$(bar) \n"; $f =~ s/\$ (?: (\w+) | \((\w+)\) )/<$^N>/xg; print $f;'

The nice variable $^N will return the value from the last matching group. When used with other less known constructs you can do some really neat things.

The following also works - but will allow for more matching groups after the $^N.

perl -e ' my $f = "\$foo \$(bar)"; our $val; # must use package global # for temporization in regex $f =~ s{\$ # the dollar (?: # outer altinator (\w+) (?{ $val = $^N }) # match and then store | \((\w+) (?{ $val = $^N }) \) # or match 2 and store ) # close outer }{<$val>}xg; print "$f\n"'

my @a=qw(random brilliant braindead); print $a[rand(@a)];