CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Simple function to format a string

 



user1982
New User

Nov 12, 2015, 4:03 AM

Post #1 of 3 (1045 views)
Simple function to format a string Can't Post

Hi,

I just need a simple function that takes a string as input and return it after format. The input string will be 1.4.0.0.10.9 and I want it as 1.4.10.9, just shift two digits on the right.

Thank you in advance.


BillKSmith
Veteran

Nov 12, 2015, 5:33 AM

Post #2 of 3 (1036 views)
Re: [user1982] Simple function to format a string [In reply to] Can't Post

It is not clear exactly what you mean. In any case, this is a job for a regular expression. The following regex solves your example correctly. It assumes that there will always be a single digit in each character position that your example has one. It further assumes that the separation characters are always periods and that they are always in exactly the same position as in your example and that no other characters are in the string.


Code
use strict; 
use warnings;
my $string = '1.4.0.0.10.9';
$string =~ s/(\d\.\d\.)\d\.\d\.(\d\d\.\d)/$1$2/;
print $string;

OUTPUT:

Code
1.4.10.9

Good Luck,
Bill


FishMonger
Veteran / Moderator

Nov 12, 2015, 6:07 AM

Post #3 of 3 (1028 views)
Re: [user1982] Simple function to format a string [In reply to] Can't Post

Another option would be to use a join/split statement.

Code
use strict; 
use warnings;

my $string = '1.4.0.0.10.9';
$string = join '.', (split(/\./, $string))[0,1,4,5];
print $string;


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives