Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning value to a * character within a hash

Tags:

hash

perl

Using the following section of code I ordinarily split a mixed string-integer field (e.g. 45A34C) and tally up instances of each letter (designated by the integer proceeding it) according to a set of rules stored in %r. This works fine.

use strict;
use warnings;

my @F; $F[5] = '*';
my @ar = split(/([ABCD])/, $F[5]);
my %r = (A => 1, B => 1, C => 0, D => 1, '*' => 0);
my $s = 0;
my $op;
my $n;
$s += $n * $r{$op} while ($n,$op) = splice @ar,0,4;

However, in some instances, $F[5] contains nothing but an asterisk - a literal * character. Any line containing this returns these warnings:

Use of uninitialized value $op in hash element at b.pl line 10.
Use of uninitialized value in multiplication (*) at b.pl line 10.
Argument "*" isn't numeric in multiplication (*) at b.pl line 10.

Which is expected given that * is not assigned a number. I've attempted to assign the character a number in the hash, but am unable to figure out the correct syntax. I've tried:

my %r = (A => 1,B => 1,C => 0,D => 1, * => 0);
my %r = (A => 1,B => 1,C => 0,D => 1, \* => 0);

But the warnings remain. What is the correct way to assign a value to a special character and why can * not be handled like 'A' can?

like image 862
AnnaSchumann Avatar asked Dec 15 '25 00:12

AnnaSchumann


1 Answers

my %r = (A => 1, B => 1, C => 0, D => 1, '*' => 0);

=> "autoquotes" its LHS when it's an identifier, but it need not be an identifier; it can be any expression. (In fact, you don't even need to use =>, which just a fancy comma (,).)


But that doesn't fix your problem. @ar only contains *, so $n is * and $op is undefined. @ar needs to have at least two values for that code to work. So let's explicitly look for values that make sense.

my %r = (A => 1, B => 1, C => 0, D => 1 );

my $s = 0;
while ($F[5] =~ /(\d+)([ABCD])/g) {
   my $n  = $1;
   my $op = $2;
   $s += $n * $r{$op};
}

By the way,

* => 0 is a weird way to write *= > 0, which means "is glob *= numerically greater than zero".

\* => 0 is a weird way to write \*= > 0, which means "is the address of glob *= numerically greater than zero".

like image 81
ikegami Avatar answered Dec 16 '25 13:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!