I am quite new to Perl, and I am writing a Perl script. A part of my script counts the number of times each word is appearing in the text file. THIS COUNTING REPEATS AFTER SPECIFIC INTERVALS, SO I NEED AN ARRAY FOR EACH OF THAT REPEATING SEQUENCE. I have the code to count the number of words, BUT FOR JUST ONE SEQUENCE.
for (@array) {
$counts{$_}++;
print "\'$_\'\t";
}
My trouble is that I need to create an array for the hash “counts”.
EDIT: By ARRAY I mean that I should be able to store the repetition for each word for each particular section of the text file. I JUST NEED TO DETERMINE THE PARTIAL COUNT FOR EACH SECTION IN THE TEXT FILE. This is what my text file looks like:!
The great thing about Perl is that there’s no need to initialize a hash or an array, you simply create one.
You say you’re a new Perl user, but you seem to know about references. You can read an excellent tutorial right inside the Perl documentation. You can do this by using the
perldoccommand from your command line.That said, and looking at your application, I can see several different types of data structures:
The code would look something like this:
The first part of the if statement is merely incrementing the section count, so that each parameter is stored in a different section. This is nice if the question is In section #x, how many times did you see Parameter “y”?.
The code would look something like this:
Another possibilities is to use a Hash of Hashes that TLP showed.
The point is that when you are talking about structure that contains more than mere scalar data, you need to use references.
How you want to construct your data structure is really up to you and depends upon what you want to track and how you want to access that data. As shown in this one question, there are at least three different ways you could structure your data. And, building this complex data structure is fairly easy. And, there’s really nothing to initialize.
Once you understand references, your data structure can be as complex as you dare (although I suggest to start looking into object oriented Perl coding techniques before you really go wild with them).
By the way, none of the answers mentioned how you’d access your data besides using Data::Dumper, but a simple loop would be sufficient. This is for an array of hashes: