How to print the next line of a match in Perl? -
so, wrote script calculates factorials of 4^(0) 4^(10) wanted test run-times, , wanted compare stirling's approximation with actual number of digits of respective factorials.
so have file data called factorials.txt contains following data example:
the factorial of 1 1 factorial of 4 24 factorial of 16 20922789888000 factorial of 64 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000
i output of factorials following:
factorial 1: 1 digits. factorial 4: 2 digits. factorial 16: 14 digits. factorial 64: 90 digits
i able write script these values, after statement factorial of ___ ... on next line value of factorial. wasn't able select next line after match, wrote using while loop through file matching nonexistence of letters, , printing length of characters on line. works, don't think it's efficient.
#!/usr/bin/env perl use strict; use warnings; use feature 'say'; $file = 'factorials.txt'; $filehandle; open($filehandle, '<', $file) or die "could not open file $_ because $!"; while(my $line = <$filehandle>) { chomp $line; $index = $.; if($line !~ m/[a-z]/) { length($line); } }
my script outputs following, example:
1 2 14 90
i want parsing script if matches word "factorial" on line, print length of characters on next line. believe must possible, can't seem figure out how go next line.
any ideas? much!
the whole thing can simpler that. need 1 specific match.
the following code check text number you've built factorial of. if finds that, print
s label. capturing number $1
. print
not have line break.
if doesn't find it, assumes whole line 1 factorial, say
s length
of line. have line break, , next output go next line.
the chomp
important length
work correctly.
use strict; use warnings; use feature 'say'; while (my $line = <data>) { chomp $line; if ( $line =~ m/factorial of ([0-9]+)/) { print "factorial of $1: "; } else { length $line; } } __data__ factorial of 1 1 factorial of 4 24 factorial of 16 20922789888000 factorial of 64 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000
and output:
factorial of 1: 1 factorial of 4: 2 factorial of 16: 14 factorial of 64: 90
Comments
Post a Comment