ggg has asked for the wisdom of the Perl Monks concerning the following question:
This is an attempt to read in the digits of PI stored in an external file.
I wanted to look at how the distribution of numbers in PI varies with increasingly large numbers of digits.
There are some web sites the have PI to a billion places.
In keeping with goal B, I want to read in the digits one-at-a-time, incrementing a hash as I go.
The only commands I could find to read in characters individually were GETC and SYSREAD; the latter looked like the best bet.
The sysread syntax is shown in line 7 and the command is in line 16, followed by 5 lines of diagnostics.
The problem is that, even though I re-declare the scalar, $digit, in each while loop, $digit is accumulating null characters - one for each loop.
The null chars are first with the digit which was read being at the end of the string of nulls.
Most of the code at this point is for trying to figure out what's going on.
Lines 17 & 21 print the length of $digit and it's contents before and after a crude attempt to remove anything from the variable that isn't a digit.
The output listing shows that I haven't altered the length at all.
So, I've got two questions: Where are the nulls coming from and why can't I regex them out of the variable (at line 19)?
#!/opt/bin/perl -w my %distr; my $i = -1; my $c = 1; # line 5 # sysread Filehandle, Scalar, Length, Offset open DF, "<Pi-00009" or die "File, DATA, is missing: $!"; print "# Before_Trim\tAfter_Trim\n"; # line 10 print "# Len\tdigit\tLen\tdigit\n"; # print "\tOffset\tLength\tScalar\n"; while ($i<=7){ my $digit; # line 15 sysread DF, $digit, $c, ++$i; print "# ",length($digit),"\t$digit\t"; $_ = $digit; s/(\d)/$1/; $digit = $_; # line 20 print length($digit),"\t$digit\n"; if ($digit =~ /[\d]/){ # print "\t",$i,"\t",$c,"\t",$digit,"\n"; $distr{$digit} += 1; }; # line 25 } close DF; __OUTPUT__ # Before_Trim After_Tri; # line 30 # Len digit Len digit # 1 3 1 3 # 2 . 2 . # 3 1 3 1 # 4 4 4 4 # 5 1 5 1 # 6 5 6 5 # 7 7 # 8 9 8 9 # 9 2 9 2
My eyes are glazing over and my mind is mush. (typical programming session for me :-} ) I'll revisit this tomorrow.
TIA
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: sysread and null characters
by Tanktalus (Canon) on Mar 24, 2005 at 04:26 UTC | |
by ggg (Scribe) on Mar 24, 2005 at 15:58 UTC | |
by Tanktalus (Canon) on Mar 24, 2005 at 16:31 UTC | |
by ggg (Scribe) on Mar 24, 2005 at 17:18 UTC | |
by Tanktalus (Canon) on Mar 24, 2005 at 18:10 UTC | |
| |
|
Re: sysread and null characters
by BUU (Prior) on Mar 24, 2005 at 06:37 UTC | |
by halley (Prior) on Mar 24, 2005 at 15:05 UTC |