Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Need to count the number of entries in a array

by Baffled (Acolyte)
on Jan 16, 2012 at 00:29 UTC ( #948038=perlquestion: print w/ replies, xml ) Need Help??
Baffled has asked for the wisdom of the Perl Monks concerning the following question:

How do I count the number of entries in this array? I wish to do the query and then determine how many items appear in the array. Such as if there is 14 items or entries in the array then I want it to give me a variable of 14. So when a supplier logs in the system counts how many items they currently have in inventory.

&oops('you do not have any items in inventory') unless (open(THEFILE, +"$basepath/$inventory/$data.txt")); my ($title, $image, $counter, $supplier, $account_num, @inventory) + = <THEFILE>; close THEFILE; chomp($title, $image, $counter, $supplier, $account_num, @inventor +y); my @supplier = split(/\[\]/,$inventory[$#inventory]); $file =~ s/\.dat//;

So the question is how many @supplier entries are there? and how do I determine that? Up front let me appoligize for what most likely is something very simple, I am learning though.

my $suppliercount = $#@supplier; ##WHAT GOES HERE TO GET ME THE + COUNT? my $inventcount = ($suppliercount + 1); print "<font face=arial size=2>You currently have $inventcount item in + inventory.</font>;

Thank you for the wisdom you share...

Comment on Need to count the number of entries in a array
Select or Download Code
Re: Need to count the number of entries in a array
by jwkrahn (Monsignor) on Jan 16, 2012 at 00:33 UTC

    An array in scalar context returns the number of elements in the array.

    my $suppliercount = @supplier;
Re: Need to count the number of entries in a array
by Marshall (Prior) on Jan 16, 2012 at 04:46 UTC
    A few comments about the code:

    1) There is no need to put '&' in front of the subroutine call. This is old Perl syntax and now means "ignore prototype". Basically don't use subroutine prototypes for your functions unless you are trying to emulate a built-in function, which I do not recommend except in rare cases. For the Perl built-in functions, you can eliminate parens, the "()" for the parameters in many, but not all cases. It is always ok to put parens in for the parameter list. Bottom line: you don't need & in front of the subroutine "oops".

    2) There are many reasons why an open() will fail...wrong permissions, etc. I would strive for a design where the "open" always works even if the file is contains nothing (NULL). File doesn't open would mean "internal program error". The program logic would have to be re-worked at bit, but there in my opinion should be a big difference between file doesn't open and "no inventory".

    3) Naming is important. THEFILE is not that descriptive. Of course this is a file! Perhaps a better name would be SUPPLIER or INVENTORY?

    4) In a case like this, the 3 argument form of open which specifies the mode explictly is probably better. open(INVENTORY,'<',$path) or die "blah..$!"; This way there is not a possiblity of $path becoming a write operation that destroys the input due to malformed input of the $basename.

    5) Perl map{} is a transformative operator and could be used to simplify my ($title, $image, $counter...,@inventory) = map{chomp; $_}<THEFILE> I've seen map{} used in place of large (30 line foreach loops), but I personally prefer this syntax only for short, clear transformations.
    Update: map{chomp} changed to map{chomp; $_} This is an important and common mistake. Ooops!

    6) In Perl, the $#version is the last "index". There are a lot of tricky Perl variables. @array in a scalar context is the number of elements in @array. for example: if (@array > 5). If I want the number of the last index, I use @array-1 instead of $#array. I've not seen a case yet where this -1 subtraction means anything significant in terms of execution time and its one less special variable to worry about.

        Please tell me what a better formulation is?

        my ($title, $image, $counter...,@inventory) = map{chomp}<THEFILE>

        Ok, I made a simple mistake, and one that is common: map{chomp} should be map{chomp; $_} The return from map is the last statement, here $_ is chomped and that result, the chomped version of $_ should be the last statement.

        Thanks for pointing this out!

Re: Need to count the number of entries in a array
by CountZero (Bishop) on Jan 16, 2012 at 07:09 UTC
    There is something I do not understand.

    You seem to have one file per supplier and this file contains (each on its own line) title, image, a counter, the supplier's name, account number, followed by an indeterminate numbers of inventory items.

    All these inventory items end up in the array @inventory. So far, so good.

    Then you split the last element of the @inventory array and the delimiter is [] ("empty square brackets" -- which is strange in itself, usually the brackets contain something ...). Why is this last element of the array @inventory "special" that you can ignore all its other elements and have to split this last one?

    Perhaps my ignorance can be remedied if you show the contents of one of your files so we can look at the file format?

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      CountZero has a good question.
      my @supplier = split(/\[\]/,$inventory[$#inventory]); same as my @supplier = split(/\[\]/,$inventory[@inventory-1]); same as my @supplier = split(/\[\]/,$inventory[-1]);
      This only looks at the last element of @inventory.

      I doubt that this is what the OP really wants.

      An example file would be very helpful.

      I would also add that if the OP has input into record format, using "|" as a .csv style record separator often works out very well for DB's that contain names or addresses.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2014-09-17 08:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (66 votes), past polls