By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,848 Members | 1,380 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,848 IT Pros & Developers. It's quick & easy.

setting range of indices in an array with a constant value

P: 51
Hi

i'd like to set a range of indices in a list with one constant value.
for example

if list = [ 1 2 3 4 5 6]

then
list(1..4,6) = 9
will change 'list' as so it now equals = [ 9 9 9 9 5 9]

i tried $list(1..4) = 9 but it only set the first index cell


how this action can be done ?
thanks,
May 11 '08 #1
Share this Question
Share on Google+
1 Reply


nithinpes
Expert 100+
P: 410
Hi

i'd like to set a range of indices in a list with one constant value.
for example

if list = [ 1 2 3 4 5 6]

then
list(1..4,6) = 9
will change 'list' as so it now equals = [ 9 9 9 9 5 9]

i tried $list(1..4) = 9 but it only set the first index cell


how this action can be done ?
thanks,
This is one way of doing it:
Expand|Select|Wrap|Line Numbers
  1. use Data::Dumper;
  2. @list=(1,2,3,4,5,6);
  3. foreach my  $el ((1..4,6)) {
  4. #find the index of the element to br replaced
  5. my ($index) = grep ($list[$_] eq $el , 0 .. $#list);
  6. splice(@list,$index,1,9);  #replace one element at that position with 9
  7. }
  8. print Dumper @list;
  9.  
May 12 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.