Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Hash slice in regex

by anjiro (Beadle)
on Sep 26, 2006 at 17:17 UTC ( [id://574986]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://574986]
Approved by grep
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2025-06-18 17:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.