
japhy
Enthusiast
/ Moderator
Jul 19, 2000, 12:24 PM
Post #2 of 3
(7165 views)
|
Re: Use of ord in s/$var/\ord/gie
[In reply to]
|
Can't Post
|
|
I don't know what inspired you to put a \ in front of ord. What your method does is, for each character matched, you replace it with a reference to the value returned by ord. ord with no arguments is ord($_), but since $_ is undefined, it's like ord(undef). That's why you're getting that 'use of uninitialized value' warning. ord(undef) is 0, so you're getting a reference to the value 0 (which is something like SCALAR(0xADDR)). If you want to use a regex, here's one method: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $str =~ s/(.)/'&#' . ord($1) . ';'/egs; # the /e means evaluate the RHS as Perl code # the /g means do this globally # the /s means that . matches EVERY character </pre><HR></BLOCKQUOTE> "RHS" is short-hand for "right hand side". I need the /s modifier here because /./ normally doesn't match a newline. If you don't want to change EVERY character then change what's inside the parens on the LHS: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $str =~ s/([\w.-])/'&#' . ord($1) . ';'/eg; # no need for the /s anymore </pre><HR></BLOCKQUOTE> There are other ways to do this, too: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $str = join '', # join with an empty string map '&#' . ord . ';', # map gets each character as $_, so ord is ok split //, $str; # split $str into a list of its characters </pre><HR></BLOCKQUOTE> Or use the HTML::Entities module (you might need to download it from http://search.cpan.org/): <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> use HTML::Entities; $str = encode_entities($str, "\000-\377"); # we want EVERY character encoded, so we pass # "\000-\377" to be used as a character class </pre><HR></BLOCKQUOTE> ------------------ Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher [This message has been edited by japhy (edited 07-19-2000).]
|