in reply to how to find the length of any line of file
Hi, welcome. Regarding your code:
#!/usr/bin/perl #<--------------------------# Where are 'use strict;', 'use warnings;' +? open $fb, "myfilename.txt"; # What if the file is missing? while ($line=<$fb>) # What if you forgot you're using $line el +sewhere? { #<------------------# Perl ignores whitespace but why be messy +? chomp($line); if ($.=<>){ # `=` is not a comparison operator! print length "$line"; # ^---------# ... and then a newline character? } # Odd indentation makes it hard to tell wh +at this matches. #<----------------------# Perl ignores whitespace but why be messy +? }
Here is a cleaned up version. I trust you to do the work of looking up the documentation for things you don't recognize, so that you learn why it's better to do it as I've shown. (But not the only way, of course!)
use strict; use warnings; use feature 'say'; # This section creates a temporary file for testing my $file = "/tmp/$0.txt"; open TMP, '>', $file or die "Died: $!"; print TMP for (<DATA>); close TMP; #-------------------------------------------------# print 'Which line would you like to measure? '; chomp( my $wanted = <STDIN> ); die 'Died: wanted line number required' if not $wanted; open my $FH, '<', $file or die "Died: $!"; while ( my $line = <$FH> ) { chomp $line; if ( $. == $wanted ) { say "The length of line $wanted ('$line') is " . length $line; last; } say "Reached end of file before line $wanted" if eof; } # remove the test file unlink $file; __DATA__ heaven heavenly heavenns abc heavenns heavennly
Hope this helps!
|
|---|