anjiro has asked for the wisdom of the Perl Monks concerning the following question:

Is there any way to force a hash slice to interpolate without spaces when used in a regex? I have a huge hash table like so:
my %k; $k{'A'} = 'Foo'; $k{'B'} = 'Bar'; $k{'C'} = 'Baz';
I want to replace all occurences of 'FooBarBaz' with something else, say "stuff". However, this doesn't work:
s/@k{qw(A B C)}/stuff/;
because it interpolates to
s/Foo Bar Baz/stuff/;
rather than
s/FooBarBaz/stuff;
This is particularly irritating because
print @k{qw(A B C)}, $/;
yields "FooBarBaz". Any thoughts? Yes, I could do
$x = join('', @k{qw(A B C)}); s/$x/stuff/;
But that's so ugly...

Replies are listed 'Best First'.
Re: Hash slice in regex
by ikegami (Patriarch) on Sep 26, 2006 at 17:21 UTC

    The equivalent print would have been print "@k{qw(A B C)}";. Remember that m/.../ is a quote-like operator. The element seperator for interpolated slices and arrays is the value of $".

    #!perl -l my %k; $k{'A'} = 'Foo'; $k{'B'} = 'Bar'; $k{'C'} = 'Baz'; { # What goes for double-quotes... print "@k{qw(A B C)}"; # Foo Bar Baz local $" = ''; print "@k{qw(A B C)}"; # FooBarBaz } { # ...also goes for the regexp operators. print qr/@k{qw(A B C)}/; # Foo Bar Baz local $" = ''; print qr/@k{qw(A B C)}/; # FooBarBaz }

    Update: Added qr/.../ to the example.

      Ah-ha! I knew there would be something like that! Too many darn man pages to wade through... =)
Re: Hash slice in regex
by hgolden (Pilgrim) on Sep 26, 2006 at 17:26 UTC
    Hey

    You want to change $". According to Programming Perl: "When an array or slice is interpolated into a double-quoted string (or the like), this variable specifies the string to put between individual elements. Default is a space".

    Hays

    Update: Too much time looking for the right page in PP makes my post redundant, but enjoy the reading from the Good Book.