Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Add - in between number in a file

by FreeBeerReekingMonk (Deacon)
on Jun 08, 2019 at 19:09 UTC ( [id://11101138]=note: print w/replies, xml ) Need Help??


in reply to Add - in between number in a file

TIMTOWTDI. Used substr() and simple functions.
#!/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)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11101138]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-25 13:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found