The above hash/grep solutions and the link to the Q&A node
How can I find the union/difference/intersection of two arrays? are both good, so i won't repeat the solution, but i will answer the other part about why your solution didn't work ..
@ar2 = @ar1[@sl];
Is an array slice setting elements of
@ar2 to elements of
@ar1 using the values of @s1 as indices. To write it out longhand, it is doing:
$ar2[0] = $ar1[ $s1[0] ];
$ar2[1] = $ar1[ $s1[1] ];
Now substitute in the values of @s1 elements:
$ar2[0] = $ar1[ 'b' ];
$ar2[1] = $ar1[ 'd' ];
And we see why it failed -- the characters
'b' and
'd' cannot be used as the index of an array. Apparently from the output, perl was cast the chars to 0 and that's why both elements are
'a'.
The last lesson here is
always use strict and warnings by default .. Adding
use warnings (or
perl -w) generates these messages:
Argument "b" isn't numeric in array slice at /tmp/r line 10.
Argument "d" isn't numeric in array slice at /tmp/r line 10.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.