perl - how to form a new array based on part of an existing array -


i trying build new array based on existing array.

#!/usr/bin/perl #join use warnings; use strict;  @names = ('jacob', 'michael', 'joshua', 'mathew'); @t_names = join ("\t" , @names); @t_names2 = join ("\t", $names[0],$names[2]); print @t_names, "\n"; print @t_names2, "\n"; 

the test script allows me join 2 elements old array form new array. if array has 1000 elements , form new array contains selective portion of 1000 elements (say, element 3 , 3 multiples). tried join ("\t", $names[0,2]) perl doesn't recognize $names[0,2] (output suggests $names[0,2] "recognized" $names[2]. , not sure error means "multidimensional syntax not supported @ join.pl"

if join not right function, other way build partial array existing array? thank you.

whenever want more 1 thing out of array, whether it's items or subset, use @ instead of $.

you can select subset of items array @arrayname[list], list list of indexes. can put literal list of comma-separated index values, can put expression returns list. ysth's solution uses expression grep $_ % 3 == 0, 3..$#names. breaking down, uses these elements:

  • $#names index of last element in @names
  • the range construct .. generate list of numbers 3 value
  • grep extract list of numbers ones matching condition
  • that condition being expression $_ % 3 == 0, means "the remainder when number divided 3 0", of course true multiples of 3

so if array has 1000 elements, $#names 999, , 3..$#names 997-element list containing numbers (3,4,5,6,7,8,...) way 999. running grep $_ % 3 == 0 on list returns 333-element list containing numbers (3,6,9,12,...) way 999, , asking @names[3,6,9,12,...,996,999] returns 333 elements located @ positions in @names array.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -