The weekly challenge 272 - Task 1: Defang IP Address

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-272/#TASK1
 3 #
 4 # Task 1: Defang IP Address
 5 # =========================
 6 #
 7 # You are given a valid IPv4 address.
 8 #
 9 # Write a script to return the defanged version of the given IP address.
10 #
11 ###  A defanged IP address replaces every period “.” with “[.]".
12 #
13 ## Example 1
14 ##
15 ## Input: $ip = "1.1.1.1"
16 ## Output: "1[.]1[.]1[.]1"
17 #
18 ## Example 2
19 ##
20 ## Input: $ip = "255.101.1.0"
21 ## Output: "255[.]101[.]1[.]0"
22 #
23 ############################################################
24 ##
25 ## discussion
26 ##
27 ############################################################
28 #
29 # There are two pretty simple approaches here. Either substitute
30 # all "." with "[.]" directly, or split the string at "." and
31 # join it using "[.]" as the glue. Both work fine.
32 
33 use strict;
34 use warnings;
35 
36 defang_ip_address("1.1.1.1");
37 defang_ip_address("255.101.1.0");
38 
39 sub defang_ip_address {
40    my $ip = shift;
41    print "Input: $ip\n";
42    $ip =~ s/\./\[.\]/g;
43    # or:
44    # $ip = join("[.]", split/\./, $ip);
45    print "Output: $ip\n";
46 }
47