473,728 Members | 1,624 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help - Counting text - Associative Array?

Greetings. I am trying to do something which should elementary for
Perl, but I have only been able to find bits and pieces on it. When I
put the bits together they do not work. Maybe I am going in the wrong
direction.

I want to count several strings of text in a file (security.txt) and
output the counts with a brief description of each. I have tried
specifying the descriptions (name) and the strings (exe) in the array
within the perl script. I can open the file to search ok, but the
counting/output doesn't work. It seems to count every line in the
file. The strings are not on their own lines in security.txt.

The goal is to see something like:

Name: Catalog Count:2
Name: Crime Count:1

Yes I am a newb, so if anyone can point me in the right direction I'd
sure appreciate it. TIA, Sam

print "\nSEARCHING... \n";

open (FILE, "security.txt") ;

print "\n";
###### Define names and their file paths ######

%exe = ( "Catalog", 'C:\Program Files\Internet Explorer\IEXPLO RE.EXE',
"Crime", 'D:\crime\Reade r\AcroRd32.exe' );

###### Try to count the occurance of file paths ######

$count=0;

while(<FILE>) {

chomp;

#if ($_ = (values %exe)) {
$count++;
}

###### print names and counts #######

foreach $key (keys %exe) {

print "Name: $key\t Count: $count\n";

}

print "\nDONE.\n" ;

close(FILE);
Jul 19 '05 #1
7 3379
On Fri, 19 Mar 2004 at 16:59 GMT, Sam Lowry <mr******@hotma il.com> wrote:
direction.

I want to count several strings of text in a file (security.txt) and
output the counts with a brief description of each.


<OP's attempt snipped>
Not too bad after all. But this works:
#!/usr/bin/perl
use strict;
use warnings;

print "\nSEARCHING... \n\n";

my %exe = (
'C:\Program Files\Internet Explorer\IEXPLO RE.EXE' => 'Catalog',
'D:\crime\Reade r\AcroRd32.exe' => 'Crime',
);
my %count;

open (FILE, "security.txt") ;
while (<FILE>) {
chomp;
$count{$_}++ if exists $exe{$_};
}
close FILE;

print "Name: $exe{$_}\t Count: $count{$_}\n" foreach sort keys %exe;
print "\nDONE.\n" ;

__END__

security.txt would need to contain something like:

C:\Program Files\Internet Explorer\IEXPLO RE.EXE
D:\crime\Reader \AcroRd32.exe
D:\crime\Reader \AcroRd32.exe
D:\crime\Reader \AcroRd32.exe

Jul 19 '05 #2
Roel van der Steen <ro*******@st2x .net> wrote in message news:<sl******* *************** @localhost.loca ldomain>...
On Fri, 19 Mar 2004 at 16:59 GMT, Sam Lowry <mr******@hotma il.com> wrote:
direction.

I want to count several strings of text in a file (security.txt) and
output the counts with a brief description of each.


<OP's attempt snipped>
Not too bad after all. But this works:
#!/usr/bin/perl
use strict;
use warnings;

print "\nSEARCHING... \n\n";

my %exe = (
'C:\Program Files\Internet Explorer\IEXPLO RE.EXE' => 'Catalog',
'D:\crime\Reade r\AcroRd32.exe' => 'Crime',
);
my %count;

open (FILE, "security.txt") ;
while (<FILE>) {
chomp;
$count{$_}++ if exists $exe{$_};
}
close FILE;

print "Name: $exe{$_}\t Count: $count{$_}\n" foreach sort keys %exe;
print "\nDONE.\n" ;

__END__

security.txt would need to contain something like:

C:\Program Files\Internet Explorer\IEXPLO RE.EXE
D:\crime\Reader \AcroRd32.exe
D:\crime\Reader \AcroRd32.exe
D:\crime\Reader \AcroRd32.exe


Dear Mr. van der Steen,

Thank you for your kind reply. Unfortunately, the strings are not
alone on their own lines in security.txt. I should have posted a
sample, thus:

3/15/2004,3:01:18 PM,Security,Suc cess Audit,Object Access ,560,SERVER\
+refterm,SERVER ,"Object Open:
Object Server: Security
Object Type: File
Object Name: C:\Program Files\Internet Explorer\IEXPLO RE.EXE
New Handle ID: 536
Operation ID: {0,178316546}

3/15/2004,1:57:28 PM,Security,Suc cess Audit,Object Access ,560,SERVER\
+Anon000,SERVER ,"Object Open:
Object Server: Security
Object Type: File
Object Name: D:\crime\Reader \AcroRd32.exe
New Handle ID: 592
Operation ID: {0,177426959}

Your code shows me the logic and syntax, and I will study it to make
sure I understand what you did. The problem now is how to see the
array values in security.txt? Do I need to use regex or index
(mentioned elsewhere but which I know nothing about)?

- I just realized something: The context of the strings in
security.txt is always the same:

Object Name:[uniform space]$exe

If I include 'Object Name: ' with the C:\... as the complete value
in the array of my script it should work, no? Not the most elegant
solution but my eyes are already crossed after working on this having
had no formal training with Perl.

What is <the right way> to do this?

Thanks for reading.

Sam
Jul 19 '05 #3
On Sat, 20 Mar 2004 at 03:04 GMT, Sam Lowry <mr******@hotma il.com> wrote:
Roel van der Steen <ro*******@st2x .net> wrote in message news:<sl******* *************** @localhost.loca ldomain>...
On Fri, 19 Mar 2004 at 16:59 GMT, Sam Lowry <mr******@hotma il.com> wrote:
> direction.
>
> I want to count several strings of text in a file (security.txt) and
> output the counts with a brief description of each.

Thank you for your kind reply. Unfortunately, the strings are not
alone on their own lines in security.txt. I should have posted a
sample, thus:


Yes, that's what I already suspected. But you didn't ask that, did you?
The best thing would be to change the algorithm a bit, but this time
I go for the minimal changes. Add

(my $search = join '|', keys %exe) =~ s/\\/\\\\/g;

before "my %count;" and change "$count{$_} ++ if exists $exe{$_};" to

$count{$1}++ if /($search)/o;

But it's not very elegant now.
Jul 19 '05 #4
Roel van der Steen <ro*******@st2x .net> wrote in message news:<sl******* *************** @195-86-124-242.dsl.easynet .nl>...
On Sat, 20 Mar 2004 at 03:04 GMT, Sam Lowry <mr******@hotma il.com> wrote:
Roel van der Steen <ro*******@st2x .net> wrote in message news:<sl******* *************** @localhost.loca ldomain>...
On Fri, 19 Mar 2004 at 16:59 GMT, Sam Lowry <mr******@hotma il.com> wrote:
> direction.
>
> I want to count several strings of text in a file (security.txt) and
> output the counts with a brief description of each.
Thank you for your kind reply. Unfortunately, the strings are not
alone on their own lines in security.txt. I should have posted a
sample, thus:


Yes, that's what I already suspected. But you didn't ask that, did you?


Yes, I did actually mention it originally, but I failed to give an
example and must take responsibility for being unclear. Het spijt me.
The best thing would be to change the algorithm a bit, but this time
I go for the minimal changes. Add

(my $search = join '|', keys %exe) =~ s/\\/\\\\/g;

before "my %count;" and change "$count{$_} ++ if exists $exe{$_};" to

$count{$1}++ if /($search)/o;

But it's not very elegant now.

My main concern is that it works and also that I understand how it
works! I will get back to you after the weekend once I've had a
chance to study it/play with it.

Sincere thanks again for your efforts.

Sam
Jul 19 '05 #5
Dear Mr. van der Steen-

Your script works great. Would you please explain 2 lines to me:

(my $search = join '|', keys %exe) =~ s/\\/\\\\/g;

I think the text of the values belonging to the keys in the array is
being joined here but I don't understand the delimiting part =~
s/\\/\\\\/g. Please explain.

$count{$1}++ if /($search)/o;

Increase the count by 1 if the string is found in security.txt. How
does this work? What is if /($search)/o doing?

I want to fully understand your script so I can make 3 modifications:

1 - If a value is not found in security.txt I want $count=0. Right
now the result is blank and I get an error if warnings is turned on.

2 - The results are not sorted. The list is in a different order every
time despite foreach sort keys(%exe) in the print line.

3 - For neatness I'd like the counts to line up in a column rather
than just tab over from the key names.

Once I understand what you did I can try to achieve these things.

For your reference here's the whole script.

TIA Sam.

####Script###

use strict;
#use warnings;

print "\nSEARCHING... \n\n";

my %exe = (

'C:\Program Files\Internet Explorer\IEXPLO RE.EXE' => 'Catalog',
'D:\crime\Reade r\AcroRd32.exe' => 'Crime',

);

(my $search = join '|', keys %exe) =~ s/\\/\\\\/g;

my %count;

open (FILE, "security.txt") ;
while (<FILE>) {
chomp;

$count{$1}++ if /($search)/o;

}
close FILE;

print "Name: $exe{$_}\t Count: $count{$_}\n" foreach sort
keys(%exe);
print "\nDONE.\n" ;
Jul 19 '05 #6
On Wed, 24 Mar 2004 at 01:14 GMT, Sam Lowry <mr******@hotma il.com> wrote:
Dear Mr. van der Steen-

Your script works great. Would you please explain 2 lines to me:

(my $search = join '|', keys %exe) =~ s/\\/\\\\/g;
This builds a part of the regex. The pipe wil function as an
OR operator. All backslashes need to be escaped because they're
special in a regex (that's the s/\\/\\\\/g).

$count{$1}++ if /($search)/o;

Increase the count by 1 if the string is found in security.txt. How
does this work? What is if /($search)/o doing?
The slashes delimit the regex, the parentheses capture the
matched string to the special variable $1. The "o" modifier
tells the Perl compiler that this regex is not expected to
change during program execution (despite the fact that there
is a variable in the regex) and that the regex only needs to
be compiled once.

I want to fully understand your script so I can make 3 modifications:

1 - If a value is not found in security.txt I want $count=0. Right
now the result is blank and I get an error if warnings is turned on.
I'd guess you need to initialise the variables then. Now I
look at my own little program again, I indeed see a problem
there. There are two possibilities: print out all the strings
that is searched for, even if they are not found, or only print
the strings that have a count greater than zero. My sample is
just in between -- and indeed buggy.

2 - The results are not sorted. The list is in a different order every
time despite foreach sort keys(%exe) in the print line.
This is also a bug. The sort is on the keys of %exe, so that
would be on the full path names, instead of the shorthand names.

3 - For neatness I'd like the counts to line up in a column rather
than just tab over from the key names.
OK. Use Anno Siegel's Text::Table for that. It's not part of
the standard Perl installation, but if you have ActivePerl,
type "ppm install Text-Table" on the command prompt to install
it.

Once I understand what you did I can try to achieve these things.

For your reference here's the whole script.

TIA Sam.


As a 3rd try I propose something like this:
#!/usr/bin/perl
use strict;
use warnings;
use Text::Table;

print "\nSEARCHING... \n\n";

my %exe = (
Catalog => 'C:\Program Files\Internet Explorer\IEXPLO RE.EXE',
Crime => 'D:\crime\Reade r\AcroRd32.exe' ,
Foo => 'Bar',
);
my %count = map {$_, 0} keys %exe;

open FILE, "security.t xt" or die $!;
while (<FILE>) {
while (my ($key, $value) = each %exe) {
$count{$key}++ if index($_, $value) > 0;
}
}
close FILE;

my $table = Text::Table->new(\'| ', 'Name', \' | ', 'Count', \' |');
$table->add($_, $count{$_}) foreach sort keys %count;
print $table->rule('-', '+'),
$table->title,
$table->rule('-', '+'),
$table->body,
$table->rule('-', '+');

print "\nDONE.\n" ;

__END__
Cheers, Roel
Jul 19 '05 #7
Roel van der Steen <ro*******@st2x .net> wrote in message news:<sl******* *************** @195-86-124-242.dsl.easynet .nl>...
On Wed, 24 Mar 2004 at 01:14 GMT, Sam Lowry <mr******@hotma il.com> wrote:
Dear Mr. van der Steen-

Your script works great. Would you please explain 2 lines to me:

(my $search = join '|', keys %exe) =~ s/\\/\\\\/g;


This builds a part of the regex. The pipe wil function as an
OR operator. All backslashes need to be escaped because they're
special in a regex (that's the s/\\/\\\\/g).

Yeah, but you forgot to quote the .

This is more effectively and more readably done as

my $search = join '|', map { quotemeta } keys %exe;

$count{$1}++ if /($search)/o;

Increase the count by 1 if the string is found in security.txt. How
does this work? What is if /($search)/o doing?


The "o" modifier
tells the Perl compiler that this regex is not expected to
change during program execution (despite the fact that there
is a variable in the regex) and that the regex only needs to
be compiled once.

The /o qualifier is dangerous - one day you may extend your program
such that $searh does change.

Much better to get into the habit of simply explicitly taking the
regex compliation outside the loop.

$search = qr/($search)/;

Note that IIRC even if you don't use qr// or /o the regex will still
only be compiled once so long as $search doesn't change.

This newsgroup does not exist (see FAQ). Please do not start threads
here.
Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1890
by: Bruce | last post by:
I don't quite understand this. $result is the result of a mysql_query. $requests = array(); while ($request = mysql_fetch_array($result)) { print("<p>"); print_r($request); array_push($requests, $request); }
3
1497
by: sudeep | last post by:
C++ Programming Language Assignment 1 Associative Array Class Problem Statement Associative arrays are a useful feature found in many languages particularly in those that are interpretive and support dynamic variables, such as awk, perl, APL, etc. An associative array is very much like the much familiar array, with the only difference that the index specified, can be of any type. (In arrays, array index HAS TO BE integer). An...
27
11201
by: Abdullah Kauchali | last post by:
Hi folks, Can one rely on the order of keys inserted into an associative Javascript array? For example: var o = new Object(); o = "Adam"; o = "Eve";
6
2017
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference between London and the previous element is 25 (40-15), London has a 25% chance of being selected. When I call the function getAssocItem to do this I need to send in 2 arguments. Is there a quick way to get the maximum key value in the associative
8
7694
by: Derek Basch | last post by:
Is there any way to associate name/value pairs during an array initialization? Like so: sType = "funFilter" filterTypeInfo = ; filterTypeInfo = new Array("type" : sType); I can do it using this: sType = "String"
7
39847
by: Robert Mark Bram | last post by:
Hi All! How do you get the length of an associative array? var my_cars= new Array() my_cars="Mustang"; my_cars="Station Wagon"; my_cars="SUV"; alert(my_cars.length);
41
4968
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in the hash are alphabetically sorted if the key happens to be alpha numeric. Which I believe makes sense because it allows for fast lookup of a key.
4
1562
by: mk834tt | last post by:
When you use an object as an assc array as in: var aa = new Array(); aa = 2.50; aa = 3.50; .... Is there a way to determine the number of entries? So far I count this way: for (var x in aa) num_in_aa++;
4
2155
by: rsaharia | last post by:
Hello All, I need help with this particular .pl file I picked up from http://www.veritools-usa.com/xnf2vhdl.htm What it's supposed to do is really convert an xnf file to a vhdl file. I need it for my fpga design work. I tried rectifying the errors that occurred - added the semicolon in line 459 , removed the brackets in line 460 and aligned the 'line' word in line 274 . This removed the compiler errors but I'm unsure of what exactly to do...
0
8896
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9416
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9269
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9192
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6012
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4523
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3231
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2647
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2159
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.