Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^2: Help with arrays

by perlguru22 (Acolyte)
on Sep 22, 2012 at 04:34 UTC ( #995036=note: print w/ replies, xml ) Need Help??


in reply to Re: Help with arrays
in thread Help with arrays

What I am having trouble understanding is how to make an array with an uknown length? I don't understand how that works sorry I am not trying to be complicated thanks =)


Comment on Re^2: Help with arrays
Re^3: Help with arrays
by perlguru22 (Acolyte) on Sep 22, 2012 at 04:38 UTC
    I had this so far
    #!/usr/bin/perl @nums = (); for(@nums) { $sum += $_; } $size = @nums; $average = $sum / $size; print "$average";
    It works when I put elements in the @nums but I am just confused on the unknown length part.

      It works when I put elements in the @nums but I am just confused on the unknown length part.
      ofcourse, the array  @nums = () is empty.
      unknown length doesn't mean EMPTY array, does it?

      Infact, your code will die with an error message, illegal division by zero at ... because the variable $size will be 0 since the array is empty.

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me
      Perl is a pretty much untyped, dynamic language. When declaring an array in Perl you don't need to specify how big you intend it to be or what it contains. It will expand and shrink at runtime depending what you do with it.
      I imagine the problem is aimed at illustrating this and ensuring that you know how to handle it.
      So, all arrays are of unknown length unless you know what you put in them or you find out with:
      $size = @nums; or $last_index = $#nums

      Perl will handle array size (memory) as needed while populating an array. The "unknown length" part becomes crucial when you have to know the number of array elements beforehand if you were to write a C, C++, or Java program to fill an array. (In latter two languages there are other data structures -- vector, set, etc. -- to avoid the need to know the number of elements beforehand).

      An exercise of an array of "unknown length" would be to populate an array from a file of unknown lines (thus number of array elements) with each number listed on a line by itself.

        "An exercise of an array of "unknown length" would be to populate ..." -- self.

        That was rather sloppy, which should have been "A related exercise would be to populate ..." (among other variations).

      @nums = (); for (0..$#nums)
      So would this be going in the right direction.
      I think what you want is  $size = $#nums;

        I think what you want is $size = $#nums;
        Probably not. $#nums is the index of the last item in the array @nums. In the usual case, that is one less than scalar(@nums), which gives you the size of the @nums array, not the index of the last element.

        --MidLifeXis

      #!/usr/bin/perl @nums = (); for(0..$#nums) { $sum += $_; } $size = $#nums; $average = $sum / $size; print "$average";
      This fix the illegal division of 0 and now it gives me the result of 0

        Anonymous Monk:
        An exercise of an array of "unknown length" would be to populate an array from a file of unknown lines (thus number of array elements) with each number listed on a line by itself.

        In the light of the above statement, let assume, your file with unknown length is given as below __DATA__, consider the codes below:

        use warnings; use strict; my $sum = 0; my @nums; # same as my @nums = (); while (<DATA>) { chomp; push @nums, $_; } $sum += $_ for @nums; my $size = @nums; my $average = $sum / $size; print $average, $/; __DATA__ 1 2 3 4 5 6

        NOTE: that @nums = () is assigning an empty list to the variable array @nums, so the array is empty. So, $size will be 0.

        You might what to check the following Up:
        push, pop, shift, unshift

        If you tell me, I'll forget.
        If you show me, I'll remember.
        if you involve me, I'll understand.
        --- Author unknown to me
Re^3: Help with arrays
by Rohit Jain (Sexton) on Sep 22, 2012 at 05:55 UTC

    You can use shift operator in this case..

    shift operator takes an array, removes an element from the start and updates the existing array

    If your array becomes empty, it returns undef, which you can handle

    sub average { $sum = shift @_; while (defined($num = shift @_)) { $sum += $num; } }
Re^3: Help with arrays
by roboticus (Canon) on Sep 22, 2012 at 12:58 UTC

    perlguru22:

    The phrase "unknown length" simply means that you (the programmer) don't know how long the array is beforehand. The intent is to make you think of a way to accomplish the task that particular bit of information. Perl, however, will always know how many items are in the array. If you build that kind of knowledge into your code, you make your code less easy to reuse.

    For example:

    sub sum_5 { # Returns the sum of array elements. # ...if your array happens to contain 5 items... my @array = @_; my $sum=0; # The programmer assume the array length right here: # v for my $i (0 .. 4) { $sum += $array[$i]; } return $sum; } sub sum_array { # Return the sum of all array elements my @array=@_; # The programmer asks the array how long it is here: vvvvvvv for my $i (0 .. $#array) { $sum += $array[$i]; } } my @a1 = (1,2,3,4,5); my @a2 = (1,2,3,4,5,6,7,8,9,10); print "** sum_5 **\n"; print "Sum of array 1 is ", sum_5(@a1), "\n"; print "Sum of array 2 is ", sum_5(@a2), "\n"; print "** sum_array **\n"; print "Sum of array 1 is ", sum_all(@a1), "\n"; print "Sum of array 2 is ", sum_all(@a2), "\n";

    As you can see, the difference between the subroutines is that in the first one, the programmer assumes that all arrays it will be used with have exactly 5 elements. In the second example, the programmer instead asks the array how long it is.

    Notes:

    • I didn't test the example code, so it likely has a bug or two.
    • This isn't the most "perlish" way of adding things up. There are better ways, but this seemed the most clear way of showing the difference between the two cases.
    • Strictly speaking, $#array doesn't tell you how long the array is, it tells you the index of the last element in it. Since perl indexes arrays using 0-based numbers, it's one less than the number of items in the array.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://995036]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2014-12-28 09:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (180 votes), past polls