Slug has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to get the following piece of code to read a file and count the instances of the and characters.

How do I tell Perl to ignore them as character classes and look for the actual character itself.

Also Is there a way to search for their ASCII representation values instead?

Thanks in advance.
open (READFILE, "<readme.txt") || die "Couldn't open file: $!"; $buffer = ""; while(<READFILE>) { #print $_; $commas++ while ($_ =~ m/,/g); $fullstops++ while ($_ =~ m/\./g); $openbracket++ while ($_ =~ m/\[/g); $closedbracket++ while ($_ =~ m/\]/g); $hyphens++ while ($_ =~ m/-/g); } print ("$commas commas\n"); print ("$fullstops full stops\n"); print ("$openbracket open brackets\n"); print ("$closedbracket closed brackets\n"); print ("$hyphens hyphens\n");

Replies are listed 'Best First'.
Re: SOLVED Please Help
by olus (Curate) on Jan 22, 2008 at 12:30 UTC
    You may want, depending on your purposes, to pay a little more attention to the fullstops parsing, as you may find the sequence '...' and not be interested in considering all of them.

    Also, you might have considered moritz's suggestion on using tr (transliteration).
    You can still do it as an exercise to an alternative of your own code.
Re: SOLVED Please Help
by GrandFather (Saint) on Jan 22, 2008 at 20:54 UTC

    You may like:

    use strict; use warnings; my $data = <<DATA; Some sample text with the odd ',', '.', '[', ']' and '-' as test input. DATA open my $inFile, '<', \$data; my %hits; while (<$inFile>) { ++$hits{$_} for split ''; } print "$_: $hits{$_}\n" for ',', '.', '[', ']', '-';

    Prints:

    ,: 4 .: 2 [: 1 ]: 1 -: 1

    Perl is environmentally friendly - it saves trees
Re: SOLVED Please Help
by thundergnat (Deacon) on Jan 22, 2008 at 20:18 UTC

    Just putzing around a bit...

    use warnings; use strict; use charnames(); my $filename = 'readme.txt'; open my $fh, '<', $filename or die "Arrgh!: $!\n"; my %ch; while (<$fh>) { $ch{$_}++ for split //; } push my @display, split //, q/.,[]-&abcde/; push @display, "\n", "\x3d", "\t"; printf "%6s - %s\n", $ch{$_} ? $ch{$_} : 0, charnames::viacode ord for + @display;