I frequently see people do simple things in the most complicated ways with dynamic languages. I suspect much of this is a carry-over from how we teach algorithms and programming in universities. If you want your code to be readable, and you want it to be maintainable long-term, then simple code tasks should be simple.
Merging Two Lists
This is simple. You've got a list of fruits, and a list of vegetables, and you want to merge them into a list called "produce."
In Perl:
my @fruits = qw/apple banana mango/;
my @veggies = qw/broccoli asparagus spinach/;
In JavaScript:
const fruits = ['apple', 'banana', 'mango']
const veggies = ['broccoli', 'asparagus', 'spinach']
Some folks will want to use iteration, or even a push()
function of some sort here, but neither is necessary. A simple assignment statement will work just fine.
In Perl:
my @produce = (@fruits, @veggies);
In JavaScript:
const produce = [...fruits, ...veggies];
Not very impressive, I know, but watch what happens when I do the same thing with associative arrays (a.k.a. Object
s, a.k.a. hashes). Now we're going to have produce items, with their colors.
In Perl:
my %fruits = (
apple => 'red',
banana => 'yellow',
mango => 'light-orange');
my %veggies = (
broccoli => 'green',
asparagus => 'green',
spinach => 'green');
my %produce = (%fruits, %veggies);
In JavaScript:
const fruits = {
apple: 'red',
banana: 'yellow',
mango: 'light-orange'}
const veggies = {
broccoli: 'green',
asparagus: 'green',
spinach: 'green'}
const produce = {...fruits, ...veggies};
It's super cool to have slick code that does neat things, but when it comes to squishing data together keeping things simple is always better.
One Exception: When you're using JavaScript, the spread operator (...
) is limited to the maximum limit supported by Function.apply()
, which (as of the time of this post) is 65,536 total values.
Anyway, I had fun writing this and I hope that your code brings you joy.
This is why you will hear experienced Perlers (Perlizens?) insist that an array is not a list. If you understand that an array is a list interpreted in numeric indexed order and a hash is a list interpreted in pairwise key value fashion, then you are more likely to perform "list" operations when beneficial. I think the Perl literature needs to do more than it already does to make a "list" a real, live actual data structure, distinct from the array and hash "storage" of lists.