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

Hi all, Been a few years since I've perl'd, and I can't remember the solution to the following: What is the shorthand way to say:
foreach (@biglonglist) { if (/(thing1)misc stuff(thing2)random garbage(thing3)/) { $x->{a} = $1; $x->{b} = $2; $x->{c} = $3; } }
I can't use split because the junk data in between my valid matches isn't consistant. I know I will always have exactly three matches. I thought that the backreferences were returned in a list, but I can't remember what that is. Thanks! f.

Replies are listed 'Best First'.
Re: pattern matching and return values
by davido (Cardinal) on Jul 18, 2004 at 05:20 UTC

    Here's an example using a simple hash (instead of a hash-ref as you're dealing with). This solution declares the hash, and then assigns to it using a hash slice. It has limitations. For example, you have to know up front how many items you're capturing. But it works pretty well.

    my $string = "This is that is other is"; my %hash; if ( @hash{'a', 'b', 'c'} = $string =~ m/(This).+(that).+(other).+/ ) { print "$_ = $hash{$_}\n" foreach keys %hash; }

    As for how to "do" a hash slice given a hash-ref, it's like this:

    @{$x}{'a', 'b', 'c'} = ( list );

    (...that is, if memory serves.)

    UPDATE: I just realized, this is my 1000th post! Enjoy!


    Dave

      Congratulations!
Re: pattern matching and return values
by saintmike (Vicar) on Jul 18, 2004 at 05:23 UTC
    If you put the match operation in list context, you can gobble up the matched items:
    if( my($a, $c) = $string =~ /(a).*(c)/ ) { print "a=$a c=$c\n"; }
    To store them in a hash,use a hash slice to assign them:
    @result{"a","b"} = $string =~ /(a).*(c)/;
      great, thanks f.
Re: pattern matching and return values
by tachyon (Chancellor) on Jul 18, 2004 at 05:43 UTC

      lame but fun; don't follow this idiom|t.

      use Data::Dumper; my $stuff = 'ASDFZXCV S;JL KJQWER QWER ZXCVO ;QLKWERQ JKL;JAPS'; my %hash; my @keys = qw( asdf qwer jkl; ); @hash{@keys} = $stuff =~ / (asdf) .*? (qwer) .*? (jkl;) /gix; print Dumper \%hash;

        I'm with you there! Just because you can does not mean you should.

        cheers

        tachyon

Re: pattern matching and return values
by Anonymous Monk on Jul 18, 2004 at 05:12 UTC
    Sorry, might be a little unclear: I'm looking for a shorthand way to assign the backreferences to a hash.

    thks again.
    f.