Rob Rob - 21 days ago 5
Perl Question

perl hash: operator expected errors

I created a hash where the keys are the symbols of a phred+33 fastq file and the values are the associated fastq scores. I am getting a lot of errors relating to operators being expected throughout the entire code. The code runs fine without the hash portions.

Here is the code:

use warnings;
use strict;

open(IN, '<', '/path/to/in_file.txt') or die $!;

my @symbols;
my $count = 0;
my %hash = (
'!' => "0",
'"' => "1",
'#' => "2",
'$' => "3",
'%' => "4",
'&' => "5",
q(') => "6",
'(' => "7",
')' => "8",
'*' => "9",
'+' => "10",
',' => "11",
'-' => "12",
'.' => "13",
'/' => "14",
'0' => "15",
'1' => "16",
'2' => "17",
'3' => "18",
'4' => "19",
'5' => "20",
'6' => "21",
'7' => "22",
'8' => "23",
'9' => "24",
':' => "25",
';' => "26",
'<' => "27",
'=' => "28",
'>' => "29",
'?' => "30",
'@' => "31",
'A' => "32",
'B' => "33",
'C' => "34",
'D' => "35",
'E' => "36",
'F' => "37",
'G' => "38",
'H' => "39",
'I' => "40",
'J' => "41",
'K' => "42"
);

while(my $fastq = <IN>){
my $length = length $fastq;
if ($length < 4180){
next
}
my $substring = substr($fastq, 4175, 10);
push(@symbols, $substring);
}
foreach (@symbols) {
my @eachsymbol = split //, $_;
$count++;
print "Sequence ", $count, "\n";
foreach my $symbol (@eachsymbol) {
if (exists $hash{$symbol}){
print $hash{$symbol}, "\n";
}
}
}


For reference, the input file looks like:
!''((((+))%%%++)(%%%%).1*-+*''))**

Thanks for your help.

Answer

Whenever you are creating hash keys that contain any non-word characters (ie. not 0-9a-zA-Z_), you must quote them:

my $hash = (
    ';' => 1,
    '*' => 2,
    '!' => 'etc',
);

Same when you access/use them:

my $x = $hash{'!'};

Also, a variable will not interpolate when using single-quotes:

$hash{'$symbol'}

Change that to:

$hash{"$symbol"};

...or better:

$hash{$symbol};