How do you match regex string replacement values ​​($ 1, $ 2, etc.) with a hash?

my (@keys,@values) = ($text =~ /\{IS\:([a-zA-Z0-9_-]+)\}(.*)\{\\IS\:([a-zA-Z0-9_-]+)\}/g);

must match these lines

{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}    
{IS:dog}bark{\IS:dog}
{IS:dog}meow{\IS:dog} #probably not a dog

which works fine, except that all the values ​​of $ 1, $ 2 and $ 3 are reset to @keys .. so I'm trying to figure out how to get these guys to get a good hash from $ 1 => $ 2 pairs ..

For the full context, what I really need , as a rule, to have a regular expression expression, returns a data structure that looks like (and adds a counter for the number of times the key was found)

{ 
  cow_1 => moo,
  cow_2 => moo,
  dog_1 => bark,
  dog_2 => meow,
}

Is there a way to use the map {} function to accomplish this with Regex? Something like this maybe?

my %datahash = map { ( $1 eq $3 ) ? { $1 => $2 } : undef } @{ regex...};

$1 $3, , ( ), $1 $2 ;

= > ,

{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}   

{cow_1}
{cow_2}

$cachedData {cow} , cow_ * % datahash...

+5
3

char:

#!/usr/bin/perl
use warnings;
use strict;

my $text = '{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}    
{IS:dog}bark{\IS:dog}
{IS:dog}meow{\IS:dog}';

my %cnt;
my %animals;
while ( $text =~ /\{IS:([\w-]+)}(.*)\{\\IS:[\w-]+}/g ){
    $animals{$1 . '_' . ++$cnt{$1}} = $2;
}

print "$_ => $animals{$_}\n" for sort keys %animals;
+2
$hash{$1} = $2 while 
        $text =~ /\{IS\:([a-zA-Z0-9_-]+)\}
                           (.*)
                  \{\\IS\:([a-zA-Z0-9_-]+)\}/gx;

(/x )

+4
  • $dataHash{cow}[$num] $dataHash{"cow_$num"}
  • -, $dataHash {cow}, , ""
    @dataHash{ grep { m/^cow_/ } keys %dataHash }
    • ( "" ) ( "1", , ).

So, I thought that was the right time to bring multi_hashinto the game.

sub multi_hash {
    use List::Pairwise qw<mapp>;
    my %h;
    mapp { push @{ $h{ $a } }, $b } @_;
    return wantarray ? %h : \%h;
}

With this idiom, you can make a hash similar to what you want like this:

my %dataHash 
    = multi_hash(  map { m/[{]IS:([\w-]+)[}]([^{]+)[{]\\IS:\1[}]/ } @lines )
    ;

This gives me:

%dataHash: {
             cow => [
                      'moo',
                      'moo'
                    ],
             dog => [
                      'bark',
                      'meow'
                    ]
           }
+1
source

All Articles