[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Code cleaning and questions



On Fri, Jun 25, 1999 at 07:39:27AM +0000, Bart Lateur wrote:
> On Thu, 24 Jun 1999 21:40:07 -0400, Ronald J Kimball wrote:
> 
> >Of course not.  This is the line that prints the ASCII value:
> >
> >print $num = ord $_;
> >
> >
> >which was part of this block of code:
> >
> >foreach (split //, $line) {
> >  print $num = ord $_;
> >  $num > 127 and warn "WARNING -- ASCII value exceeds 127.\n";
> >}
> 
> Should I really remind you that "print $num" prints to STDOUT, and
> warn() to STDERR? MacPerl merges those two filehandles, but NOT
> immediately. So those results will be printed intertwined, but not close
> together. The relationship between the two things in the output won't be
> apparent.

I was showing a more Perlish way of writing the code provided, i.e. using
split and foreach rather than for and substr.  I am aware that print prints
to STDOUT by default, and that warn prints to STDERR.

On the other hand, it would make sense for the original poster to rewrite
his code so the warnings are more useful.


> Actually, what I would do if it was for me, is count the occurences of
> all unacceptable characters, and print out a summary of the warning
> afterwards.
> 
> Something like:
> 
> 	while(defined($line=<>)) {
> 		my $wacky = $line;
> 		$wacky =~ tr/\200-\377//cd; # delete normal
> 		foreach $ord (unpack('C*', $wacky)) {
> 			$wacky[$_]++;
> 		}
> 	}
> 	if(@wacky){
> 		local $" = "\n";
> 		warn <<EOT;
> WARNING! Illegal characters found!
> @{[ map { "** $_ => $wacky[$_]" } 
>    grep { $wacky[$_] } 0 .. $#wacky ]}
> EOT
> 	}

This looks like a more useful way of checking for illegal characters,
especially if there are a whole lot of them.


> Ooh, that's right. Your construction
> 
> 	foreach (split //, $line) {
> 	  print $num = ord $_;
> 	}
> 
> is equivalent to
> 
> 	foreach $num (unpack('C*',$line)) {
> 	  print $num;
> 	}
> 
> TIMTOWTDI.

Not surprisingly, the code using unpack() is much more efficient.


Ronald

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org