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

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

  • Comment on Re5; Is a global variable better than repetition within variables?
  • Download Code

Replies are listed 'Best First'.
Re: Re5; Is a global variable better than repetition within variables?
by danger (Priest) on Jan 28, 2002 at 03:51 UTC

    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.