develooper Front page | perl.beginners | Postings from December 2002

Production worthy "Learning Perl" regex exercise solution?

Thread Next
Lance Murray
December 26, 2002 11:50
Production worthy "Learning Perl" regex exercise solution?
Message ID:

I'm trying to work through the "Learning Perl" Llama book, but I'm a bit
stumped on one of the regex exercises (ch 8.6 #3).  The solution at the back of
the book doesn't work if you don't presume anything for input.

Anyway, what the book asks is to write a regular expression that will parse a
file for scalar variables.  I've found its not so easy, particularly if you
don't want to presume anything on the input, e.g.:

# Given a file, e.g.: ~/filetoparse.txt  (exclude comments)
$0                   # "shouldn't match special variables like $0"
$the1stScalar        # OK
$$notaScalar         # improper syntax
  $the2ndScalar .    # preceeding or trailingspaces or tabs OK
thisis$notaScalar    # improper syntax
$the3rdScaler = $the4thScalar  # multiple variables OK
$thisIsNOT@scalar $the5thScaler the end.  # invalid character (@)

# The output I'm trying to get to:

Anyway, I've racked my brain for days, and I still can't get very close.  A key
issue seems to be matching a variable at the beginning of the line (^ anchor?)
OR preceded by \s character.  This is the code/regex snippets I"m using to test
my attempts, and few of the examples I've tried (commented out:

#!/usr/usperl -w
### Yes its ugly, but it all works for my purposes here
use strict;while(<>){chomp;if(
### Uncomment regex to test
# /\$([\w])+/
# /\$[a-zA-Z_]+[a-zA-Z_\d]*/
# /\s\$[a-zA-Z_]+[a-zA-Z_\d]*/
# /( |\t|^\w)\${1}[a-zA-Z_]+[a-zA-Z_\d]*\b/
/^\$[A-Za-z_]\w*$/    # example from back of book doesn't work well
){print "$&\t\t$`$&$'\n";}}

Maybe somebody has some ideas I haven't thought of?  I could probably spring
for a Carl's Jr "$6 dollar burger & Lord of the Rings "The Two Towers" ticket
(all via-Paypal) if anyone has a solid solution.



print "Lance Murray, Information and Communications Systems\n",  # department
"The Church of Jesus Christ of Latter-Day Saints\n",  # employer and religion
"(801) 240-6583, murraylk\\n\n",  # work phone number and email
"\"Better to do a little well than a lot poorly\" (Socrates)\n"; # philosophy
@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{
($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{$_}=~/^[P.]/&&
close$_}%p;wait until$?;map{/^r/&&<$_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print

This message may contain confidential information, and is intended only for the use of the individual(s) to whom it is addressed.


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About