How to get the a list to show zeros for empty entries in Perl?

perl

Solution

Your approach is correct, but there's an issue with your `zeros()` function. You are calling it with `@abc` as a parameter, which makes a copy of that list. You then change the copy. At the end of the sub, that copy is discarded. In your `checking()` function, you are still using the original list.

You can fix it like this:

sub zeros {
  my @list = @_;
  @list = map { $_ // 0 } @list;
  return @list;
} 

@abc = zeros(@abc);
checking(@abc);

The trick is to return the altered list and reassign it to the original variable.

If you had used `strict` and `warnings` it would have told you about that:

Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28. List =  index = 0

index = 1 3 index = 2

index = 3

index = 4

index = 5 5

Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28. 
Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28. 
Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28.

But since you are dealing with a very big array, I would advise to use an array reference instead because the copying will be expensive.

sub zeros {
  $_ //= 0 for @{ $_[0] };
} 

zeros(\@abc);
checking(@abc);

Problem

Originally, I am working with a list with length = 2^16. However, to abstract this, I will set length = 5 in this example. ``` #subroutine to make undefined entries -> 0 sub zeros { foreach(@_) { if(!defined($_)) { $_ = 0; } } } #print out and indicies and elements of list sub checking { print "List = \n"; my $counter = 0; foreach (@_) { print "index = $counter\n"; print "$_\n"; $counter += 1; } print "\n"; } ``` Method 1: If I access different indices to edit the element, I get the following when I print out the arrays. I dont want to see blank. I want them to be 0. I have already set up a subroutine "zeros" to make undefined entries become zero. But I dont know what went wrong in my code. I have also tried "$_ += 0" for each elements of the list. I still wasnt able to get zeros for empty entries. ``` #method 1 @abc = (); $abc[1] = 3; $abc[5] = 5; &zeros(@abc); &checking(@abc); List = index = 0 index = 1 3 index = 2 index = 3 index = 4 index = 5 5 ``` And method 2: I can get zeros if I initialise the list like this. But as I said, I am working with very long list, I cannot definitely not initialise my list like this. ``` #method 2 @abc = (3,0,0,0,5); &checking(@abc); List = index = 0 3 index = 1 0 index = 2 0 index = 3 0 index = 4 5 ```

Original source

Related problems