in reply to Re: (Ovid) Re: Is a global variable better than repetition within variables?
in thread Is a global variable better than repetition within variables?

Just a bit of weekend golf/obfu....
s//$prefix/for values%hash;

-Blake

  • Comment on Re: Re: (Ovid) Re: Is a global variable better than repetition within variables?
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: (Ovid) Re: Is a global variable better than repetition within variables?
by Anonymous Monk on Jan 27, 2002 at 20:47 UTC
    I was about to suggest that too, just for fun. But I chose not to. Didn't want to start a golf/obfu thread. :)

    Anyhow, there's a bug in your code. You need to have something as pattern. Otherwise the empty pattern magic will kick in.

    -Anomo
      What bug are you talking about? We want the empty pattern "magic" to kick in... at least the magic where it matches the emptyness sitting infront of a string. Thats how we add the prefix to each value in the hash...
      #!/usr/bin/perl -wT use strict; my $prefix = 'dog'; my %hash = map {++$;,$_} (qw(ged house ma matic),''); print "Before:\n"; print "$_ => '$hash{$_}'\n" for keys %hash; s//$prefix/for values%hash; # Add the Prefix... print "\nAfter:\n"; print "$_ => '$hash{$_}'\n" for keys %hash; __END__ Before: 1 => 'ged' 2 => 'house' 3 => 'ma' 4 => 'matic' 5 => '' After: 1 => 'dogged' 2 => 'doghouse' 3 => 'dogma' 4 => 'dogmatic' 5 => 'dog'

      -Blake

        Probably referring to the magic of: if you use an empty pattern then the last successfull pattern match is re-used. Doesn't show up in your example, but could catch someone unawares:

        #!/usr/bin/perl -w use strict; # this messes up the intended empty pattern later: $_ = 'match'; /m/; my $prefix = 'dog'; my %hash = map {++$;,$_} (qw(ged house ma matic),''); print "Before:\n"; print "$_ => '$hash{$_}'\n" for keys %hash; s//$prefix/for values%hash; # Add the Prefix... print "\nAfter:\n"; print "$_ => '$hash{$_}'\n" for keys %hash; __END__ output: Before: 1 => 'ged' 2 => 'house' 3 => 'ma' 4 => 'matic' 5 => '' After: 1 => 'ged' 2 => 'house' 3 => 'doga' 4 => 'dogatic' 5 => ''

        That could be easily fixed by using s/^/$prefix/ rather than the empty pattern in this case.

        Update: just for reference, the relevant documentation is in perlfunc under the /PATTERN/cgimosx operator:

        If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead.