Site menu:

Back to examples

Perl Example - Edit Grub

#################################################
#Version 0.1                                    #
#Free to use for any purpose                    #
#No credits or backlink required                #
#Author : Shaji Kalidasan (shajiindia@yahoo.com)#
#################################################

use 5.010;
use autodie;

unless(@ARGV == 1){
	die "Insufficent arguments - Usage: $0 <filename>";
	#Example perl edit-grub.pl grub-config
}

#Please add combinations to this config file
my $config_file = "combinations.ini";

#Read from combinations.ini if exists otherwise default to local array
my @combinations = ("acpi=off", "pci=nomsi", "quiet");
if(-e $config_file){ 
    @combinations = ();
    open COMBINATIONS,'<',$config_file;
    while(<COMBINATIONS>){
        chomp;
        push @combinations,$_;
    }
}

$^I = '~';
while(<>){
    if(/(.*\s)(\S+)\s*\Z/){
        if($2 ~~ @combinations){
            my $opt = options();
            if($opt == -1){
                say ARGVOUT "$1$2";
            }else{
                say ARGVOUT "$1$opt";
            }
        }else{
            print ARGVOUT $_;
        }
    }
}	

sub options {
    select STDOUT;
    say '*' x 52;
    say "     Please choose an option from 0 through $#combinations";
    foreach my $index (@combinations) {
        say "     $index. $combinations[$index]";
    }
    say '*' x 52;
    print "Enter your choice [0 through $#combinations] :";
    chomp(my $option = <STDIN>);
    given($option){
        when('0'){
            return $combinations[0];		
        }
        when('1'){
            return $combinations[1];		
        }
        when('2'){
            return $combinations[2];		
        }
        default{
            say "Please enter a value in the range 0 through $#combinations";
            return -1;
        }
    }
}