Searching Array - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Searching Array

jb03jb03 Posts: 5Member
I'm trying to search in an array for characters other than letters. I've done this kind of operation in other languages, but PERL is new to me. Below is my code.

open INFILE, 'test.txt' or die "File Not Found
";
@array[chr()] = ;
close INFILE;

$count = 0;
for ($i = 0; $i < length(@array); ++$i)
{
if (@array[chr($i)] == "i")
{
++$count;
}
}

print $count;

Textfile 'test.txt is as follows:
This is a test.
How about those Mets.
This is neat and cool.
Spontaneous combustion is cool.

My output is: 1
The array only has one value, which is the text file, istead of the text file's individual characters.
For example:
@array[0] = "T"
@array[1] = "h"
@array[2] = "i"
@array[3] = "s"
and so on . . .

Comments

  • JonathanJonathan Posts: 2,914Member
    : I'm trying to search in an array for characters other than letters.
    : I've done this kind of operation in other languages, but PERL is new
    : to me. Below is my code.
    :
    : open INFILE, 'test.txt' or die "File Not Found
    ";
    : @array[chr()] = ;
    @array = ;

    : close INFILE;
    :
    : $count = 0;
    : for ($i = 0; $i < length(@array); ++$i)
    : {
    : if (@array[chr($i)] == "i")
    That won't work...you need to do:-

    chomp $array[$i]; # Get rid of
    on the end of the line
    if ($array[$i] =~ /W/) # Look for non-alphanumerics

    : {
    : ++$count;
    : }
    : }
    :
    : print $count;
    :
    : Textfile 'test.txt is as follows:
    : This is a test.
    : How about those Mets.
    : This is neat and cool.
    : Spontaneous combustion is cool.
    Unless it happens to you personally. Having said that, it'd be one hell of a cool way to go when the time was right!

    : My output is: 1
    Well, the above outputs 4, as there are 4 lines containing a character other than a letter. So maybe I can't really tell what you're wanting to do.

    : The array only has one value, which is the text file, istead of the
    : text file's individual characters.
    : For example:
    : @array[0] = "T"
    : @array[1] = "h"
    : @array[2] = "i"
    : @array[3] = "s"
    : and so on . . .
    Each line of the file gets read into one array element.
    $array[0] = "This is a test.
    ";
    $array[1] = "How about those Mets.
    ";
    $array[2] = "This is neat and cool.
    ";
    $array[3] = "Spontaneous combustion is cool.
    ";

    Note $ when we're referring to an element, not @. @ is when we're talking about the array as a whole, or a slice of the array, not an individual element.

    Jonathan

    ###
    for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
    (tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
    /(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");

Sign In or Register to comment.