On Sat, Mar 14, 2009 at 08:28, M. Coiffure <coiff...@gmx.at> wrote:
> Hi all
>
> I'm getting this error on the following (test) script:
>
> Can't call method "x" without a package or object reference at test.pl line 
> 12 <ENT> line 1
snip
>        $ent{$1} = \x{$2};
snip

The \x{hex value} literal syntax only works in side of strings and
only works with constant values (i.e. "\x{00E1}" never
"\x{$somevalue}").  The way you convert numbers to characters in Perl
is the chr function*.  It takes an offset into the character set (In
this case UNICODE) and returns the character at that offset.  You have
one other issue, that offset is specified in decimal, not hexadecimal,
so you will need to convert the hexadecimal value "00E1" into its
decimal value 225.  Happily there is a function in Perl to do this:
hex**.  So instead of saying

    $ent{$1} = \x{$2};

you should say

    $ent{$1} = chr hex $2;

Some other things to watch for:
    * bareword filehandles have many issues, use lexical filehandles instead
    * the two argument version of open has issues, use the three
argument version instead
    * why use $1 and $2 when you store the captures directly to scalars
    * never try to use values gotten from a regex without testing to
see if the regex was successful

Here is how I would write the code:


#!/usr/bin/perl

use strict;
use warnings;

open my $ent, "<", "entities.txt"
        or die "cannot read entities: $!";

my %ent;
while (<$ent>) {
        #skip any lines that don't match what we want
        next unless my ($entity, $ordinal) = /^(\S+)\s+(\S+)$/;
        $ent{$entity} = chr hex $ordinal;
}

print "$_ => $ent{$_}\n" for sort keys %ent;


* http://perldoc.perl.org/functions/chr.html
** http://perldoc.perl.org/functions/hex.html

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to