Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Failed array attemp

by tobyink (Canon)
on May 13, 2012 at 21:37 UTC ( [id://970339]=note: print w/replies, xml ) Need Help??


in reply to Failed array attemp

You mean like this?

push @z, (grep { $_ ~~ \@y } @x) ? 'y' : 'n';

Shifting some of that into a sub might make it a little more readable...

sub arrays_intersect { grep { $_ ~~ $_[1] } @{$_[0]} } push @z, arrays_intersect(\@x, \@y) ? 'y' : 'n';

Or you could use Set::Scalar...

my $x_set = Set::Scalar->new(@x); my $y_set = Set::Scalar->new(@y); push @z, $x_set->intersection($y_set)->empty ? 'n' : 'y';
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: Failed array attemp
by Anonymous Monk on May 13, 2012 at 21:46 UTC
    Looks like exactly what I want but does not work. I got rid of syntax error by substituting ~~ with == but the results is wrong.
    @x = qw(1 4); @y = qw(1 2 3); push @z, (grep { $_ == \@y } @x) ? 'y' : 'n'; print $z[0]; print $z[1];

    $z[0] gives me now and $z1 is uninitilised.

      The ~~ was intentional. It's the smart match operator. == won't cut it.

      Smart match was introduced in Perl 5.9.3, about 6 years ago.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
        What if I have perl v5.8.5 (company provided and cannt upgrade)?

      You have to be using perl v5.10 or higher to use the smartmatch operator (~~).

      I keep getting syntax error and can't change the version so it must be old. Sorry to bother but anyway of making this work without smart catching? (can change slightly by I will be using this scheme a lot so I like the one line clean code. Thanks again.
      push @z, (grep { $_ ~~ \@y } @x) ? 'y' : 'n';

        If you are going to be "using this scheme a lot", I'd recommend you upgrade, or re-review this post I wrote which is similar to your original code in your question but it actually works.

        Admittedly, I didn't even think to use smartmatch, so kudos to tobyink for that.

        Without smartmatch, I believe you have to do it in two steps.

        I guess no other way. Can't really upgrade as I am working on a server and I am not an admin. Thanks steveib I will just use what you wrote :).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2024-04-25 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found