in reply to Add - in between number in a file
#!/usr/bin/perl use strict; use warnings; while (my $line = <DATA>){ chomp($line); $line = "0" . $line while length($line) < 9; my $first = substr($line, 0, 3); my $second= substr($line, 3, 2); my $third = substr($line, 5, 4); my $str = $first . '-' . $second . '-' . $third; print $str . "\n"; } __DATA__ 458430764 453453214 462634878 453990002 462755714 631036456 466917461 467172570 454691673 258611036 42
I have added an extra check, just in case it is a smaller number and not the 9 numbers, we put "0" in front of our read $line. but know that Perl handles the numbers in the files as strings, only when you start doing mathematical operations with them, then Perl automatically handles them as numbers. You can also just print a warning and skip, like so:
if(length($line) != 9){ warn "Bad data read (at line $.): '$line' length is not correct.\n"; next; # skip processing this line } if ($line !~ /^\d+$/){ warn "Bad data read (at line $.): '$line' not numerical.\n"; next; # skip processing this line }
edit: added latter check. Assuming we have positive integer numbers only (no E or negative numbers, no floats)
|
---|