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

Hi All, I'm trying to match the first leter in a string after i pull the string from a hash table. Here is a peace of the code.
################# # PRINT RESULTS # ################# while ($db->FetchRow()) { if(($row>=$min)&&($row<$max)) { my (%dbrow) = $db->DataHash(); # Change the color of the row my $bgcolor="#E6E6D7"; if ($color % 2 !=0) { $bgcolor = "#DDDDDD"; } my $title="$dbrow{'Title'}"; if ($title =~ /^$layer/) { do something... } } }
So if the first letter in the title is "A", then i will print out all the records where that's true. Right now i'm not getting anything. I don't think that i'm doing the match correctly. Someone Please Help. Thanxs - Kiko

Replies are listed 'Best First'.
Re: Matching the first letter in a string
by myocom (Deacon) on Jul 31, 2001 at 02:49 UTC

    If you're going to match a fixed number of letters in a fixed position (e.g., the first letter), use substr instead:

    if (substr($title,0,1) eq $layer) { # do something... }

    If you want the items checked regardless of case (that is, 'a' is treated the same as 'A'), force it to be lowercase:

    if (lc(substr($title,0,1) eq lc($layer)) { # do something... }

    As a side note, you're doing some extraneous quoting in there too, on the assignment to $title. I'd suggest changing that line to:

    my $title = $dbrow{Title};

      The original question concerned the first letter of $title, whereas your answer compares the first character.

      To match the first letter case insensitively, try:

      my $title="$dbrow{'Title'}"; $title =~ m/([a-z])/i; # Match the first letter in $title if (lc($1) eq lc($layer)) { #do something... }
      NB. I'm using [a-z] rather than \w because \w includes the underscore character, which isn't a letter.

      Given that you seem to be working with results returned from a database, it's almost certainly better to check the first letter matches in the SQL query, rather than in the Perl code later on. Try something like SELECT * FROM table WHERE field LIKE "A%" to match records where field starts with the letter A.