Adding a line to /etc/hosts via Perl

Having appended a line to /etc/hosts through BASH, what I really wanted to do, was add it via PERL.

The basic operation would be the same: load a text file into a single variable, search a string for text, and if not found append text to a file in Perl.

So, here is the conversion of that earlier bash script:

#!/usr/bin/perl
# Configure environment to promote good programming practices
use strict;
use warnings;

# Define initial variables & constants
use constant NOT_FOUND => -1;        # All good programmers use Constants
my $domain="example.com";            # Change it to meet your needs
my $needle="www.$domain";            # I search with www. prefix
my $hostline="127.0.0.1 $domain www.$domain";
my $filename="/etc/hosts";           # Standard host file location

# Read the file into a scalar var in the most backwards compatible way
local( $/, *FILEHANDLE );
open(FILEHANDLE, $filename) or die("Cannot access $filename");
my $haystack = ;
close(FILEHANDLE);

# Look for the domain in the file already
my $result = index($haystack, $needle);

# Index returns 
if ( $result == NOT_FOUND )
{
  print "$needle NOT found in $filename\n";
  # If the line wasn't found, add it using an echo append >>
  open(FILEHANDLE, ">>" . $filename);
  print FILEHANDLE $hostline . "\n"; #write newline
  close(FILEHANDLE);
  print "$hostline added to $filename\n";
} 
else
{
  print "$needle already exists in $filename\n";
}

As a refresher on PERL, implied lessons in this are:
To concatenate strings in PERL you can either embed them within the double quoted string or concat them with the period like PHP does.
Lines end in semicolons of course
If causes change from brackets and fi in BASH to parents and braces in PERL
Constants are done with “use constant”
vars are usually defined with a my like basics var – there are of course variations on this.
Print vs echo
comparisons get the double = as in php

Add a Comment

Your email address will not be published. Required fields are marked *