Slices aren't illegal:
@slice = @myarray[1, 2, 5];
@slice = @myhash{qw/foo bar baz/};
And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not.
To just merge the arrays (without removing duplicates)
ES5 version use Array.concat
:
var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
console.log(array1.concat(array2));
const array1 = ["Vijendra","Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = [...array1, ...array2];
Since there is no 'built in' way to remove duplicates (ECMA-262 actually has Array.forEach
which would be great for this), we have to do it manually:
Array.prototype.unique = function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
Then, to use it:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique();
This will also preserve the order of the arrays (i.e, no sorting needed).
Since many people are annoyed about prototype augmentation of Array.prototype
and for in
loops, here is a less invasive way to use it:
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));
For those who are fortunate enough to work with browsers where ES5 is available, you can use Object.defineProperty
like this:
Object.defineProperty(Array.prototype, 'unique', {
enumerable: false,
configurable: false,
writable: false,
value: function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
});
Best Answer
My original answer posted working code, but didn't really explain the problem with yours. This is expanded a bit to correct that. Your example had two problems. First, you had a problem when making the reference. You need to use
[ ]
instead of the standard parentheses in order to create a reference (to an anonymous array). Second, when you tried to get at the reference, you left off one set of brackets. You want to put the reference itself inside@{ }
in order to get at the whole array. (Also, and this may be a typo: you have no$
beforefilecontents
.)The code here is essentially from
perldoc perldsc
. I highly recommend it. Also very useful if you're new to references in Perl isperldoc perlreftut
. Both tutorials discuss how to make and get at references in a variety of situations. Finally, you can find a good cheat sheet for references in a post on PerlMonks.