#!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub read_hosts { my $file = "/etc/hosts"; open (my $fh, "<", $file) or die "Can't open $file for read: $!"; my @hosts = <$fh>; close $fh or die "Cannot close $file: $!"; return @hosts; } sub write_hosts { my $file = "/etc/hosts"; open (my $fh, ">", $file) or die "Can't open $file for read: $!"; for my $host (@_) { print $fh $host; } # Or print $fh $_ for (@_); close $fh or die "Cannot close $file: $!"; return; } my @hosts = read_hosts; print Dumper \@hosts; $hosts[2] = "Test_host\t127.0.0.4\n"; write_hosts(@hosts); my @updates = read_hosts(); print Dumper \@updates; __END__ sudo perl hosts.pl $VAR1 = [ '127.0.0.1 localhost ', '127.0.1.1 user ', '# The following lines are desirable for IPv6 capable hosts ', '::1 ip6-localhost ip6-loopback ', 'fe00::0 ip6-localnet ', 'ff00::0 ip6-mcastprefix ', 'ff02::1 ip6-allnodes ', 'ff02::2 ip6-allrouters' ]; $VAR1 = [ '127.0.0.1 localhost ', '127.0.1.1 user ', 'Test_host 127.0.0.4 ', '::1 ip6-localhost ip6-loopback ', 'fe00::0 ip6-localnet ', 'ff00::0 ip6-mcastprefix ', 'ff02::1 ip6-allnodes ', 'ff02::2 ip6-allrouters' ];