Wednesday, December 21, 2022

Find the number of repeatition of each word in a file using bash script without using array

#!/usr/bin/bash
echo "Please enter a sentence"
read sentence
for word in $(echo $sentence|xargs -n 1 |sort -u )

do
#occurance=$(echo $sentence | grep -i -o "$word"  | wc -w)

echo -e "$word-$(echo $sentence | grep -i -o "$word"  | wc -w)"



done

Thursday, December 15, 2022

Find highest and lowest number in an unsorted array using bash script

 #!/usr/bin/bash
#declare -a sports=([0]=football,[1]=cricket,[2]=hockey,[3]=basketball)
#sports[0]=foorball
#sports[1]=cricket
#sports[2]=hockey
#sports[3]=basketball

#echo "${sports[@]}"
echo "Please enter 5 marks of 5 students"
#for i in $(seq 0 4)
for i in {0..4}
do
read numbers[$i]
done
((max=${numbers[0]}))
((min=${numbers[0]}))
#echo "max is $max"
#echo "min is $min"
#echo "${numbers[@]}"
for i in ${numbers[@]}
do
if [ $i -gt $max ]
then
max=$(($i))
fi
if [ $i -lt $min ]
then
min=$(($i))
fi
done

echo "The highest number in the array is $max"
echo "The smallest number in the array is $min"

Find the number of repeatition of each word in a file using bash script

 #!/bin/bash
#input="./maharshi.txt"
#xyz=$1
#while read -r line
#do
#echo -e "$line"
#done <$xyz
declare -A words
file=$(cat ./maharshi.txt)
for line in $file
do

#echo -e "$line"
for word in $line
do
((words[$word]++))
done
done

for i in "${!words[@]}"
do
echo "$i " "${words[$i]}"
done



Monday, December 12, 2022

finding factorial of a number using bash one liner

 read -rep $'enter the number whose factorial you want\n' fact && result=1 && for i in $(seq 1 $fact) ;do result=$((result*i));don
e && echo $result

 

 

read -rep $'enter number\n' num && (echo 1; seq $num) | paste -s -d "\*" | bc

Performing x to the power of y in bash

sourav@LAPTOP-HDM6QEG8:~$ a=2
sourav@LAPTOP-HDM6QEG8:~$ b=8
sourav@LAPTOP-HDM6QEG8:~$ echo "$((a**b))"

Write a shell script to print all the multiplication tables (up to 10) between two given numbers

#!/bin/bash
echo "Enter first number"
read first
echo "Enter Second number"
read second

for ((i=first;i<=second;i++))
do
for((j=1;j<=10;j++))
do
echo  "$i * $j =  $((i*j))"
done

done

 

 using an one liner

 

read -rep $'Enter value of first\n' first && read -rep $'Enter value of second\n' second && for i in $(seq $first $second); do for j in $(seq 1 10); do echo "$i*$j=$((i*j))"; done;done

Wednesday, December 7, 2022

An one liner to print a table for the number given as input in bash

read -rep $'Enter value of j\n' j && for i in $(seq 10);do echo "$i * $j = "$(($i*$j)); done


otherwise the program would be something like


#!/bin/bash
clear
echo "input number :"
read x
echo
for i in 1 2 3 4 5 6 7 8 9 10
do
#t=`expr $x \* $i`
#echo $t
echo $(( x * i))
i=`expr $i + 1`
done

Tuesday, December 6, 2022

Calculating factorial using bash one liner

 

I was trying to get the factorial of a number in bash,it's an easy program obviously ,using loop I can do this,for example

#!/usr/bin/bash
echo "Enter number"
read number

result=1
for((i=1;i<=number;i++))
        do
                result=$(($result*i))
        done
echo "The factorial of $number is $result"

Then I tried to find some one liners,I mean bash is famous for one liners ,using seq and bc it worked just fine.

sourav@LAPTOP-HDM6QEG8:~$ num=5
sourav@LAPTOP-HDM6QEG8:~$ seq -s "*" 1 $num | bc
120

Using $(( it also worked like it should

sourav@LAPTOP-HDM6QEG8:~$ echo $((`seq -s "*" 1 $num`))
120

However when I am trying to use expr I am not able to do it.

sourav@LAPTOP-HDM6QEG8:~$ expr `seq -s " * " 10`
expr: syntax error: unexpected argument ‘0’

I thought since * is an universal symbol may be I should escape it,but it still does not work

sourav@LAPTOP-HDM6QEG8:~$ expr `seq -s " \* " 10`
expr: syntax error: unexpected argument ‘\\*’

However I am able to perform the summation though like this

sourav@LAPTOP-HDM6QEG8:~$ expr `seq -s " + " 10`
55

So why I am getting an error when trying to get the multiplication of a series using expr,can someone explain please??

Friday, December 2, 2022

Calculate total size of all the text files in current directory in bash

 du -bc *.txt | tail -1 | cut -f 1

 if the extension is variable

ext="txt"

du -bc *.$ect | tail -1 | cut -f 1


Source: https://unix.stackexchange.com/questions/72661/show-sum-of-file-sizes-in-directory-listing

Concatenate strings in bash shell script

 #!/bin/bash

echo "Enter first string"

read string1

echo "Enter second string"

read string2

echo "$string1 $string2"


Basic calculator in bash script



echo "Enter operation to be performed so that first number operation second number"

read operation

case $operation in

+)

result=`echo "scale=2; $first + $second" | bc`

;;

-)

result=`echo "scale=2; $first - $second" | bc`


;;

\*)

result=`echo "scale=2; $first * $second" | bc`


;;

/)

result=`echo "scale=2; $first / $second" | bc`


;;

*)

result="Not valid"

;;

esac


echo "Result is $result"


switch case example in bash script

#! /bin/bash


echo -en "Enter your logins\nUsername: "

read user_name 

echo -en "Password: "

read user_pass 

while [ -n $user_name -a -n $user_pass ]

do


case $user_name in

    ro*|admin)

        if [ "$user_pass" = "Root" ];

        then

            echo -e "Authentication succeeded \ n You Own this Machine"

    break

        else

            echo -e "Authentication failure"

            exit

        fi

    ;;

    jenk*)

if [ "$user_pass" = "Jenkins" ];

then

echo "Your home directory is /var/lib/jenkins"

    break

else

        echo -e "Authentication failure"

fi

        break

    ;;

    *)

        echo -e "An unexpected error has occurred."

        exit

    ;;

esac


done


Source: BASH "switch case" in Linux with practical example - Linux Cent

why echo --help not opening the help page of echo in bash

 man echo relates to the echo program. GNU echo supports a --help option, as do some others. When you run echo in Bash you instead get its builtin echo which doesn't.

To access the echo program, rather than the builtin, you can either give a path to it:

/bin/echo --help

or use Bash's enable command to disable the built-in version:

$ enable -n echo
$ echo --help

Bash has built-in versions of a lot of basic commands, because it's a little faster to do that, but you can always bypass them like this when you need to.


Source: https://unix.stackexchange.com/questions/153660/why-echo-help-doesnt-give-me-help-page-of-echo

Meaning of -n in bash

 


The -n argument to test (aka [) means "is not empty". The example you posted means "if $1 is not not empty. It's a roundabout way of saying [ -z "$1" ]; ($1 is empty).

You can learn more with help test.

$1 and others ($2$3..) are positional parameters. They're what was passed as arguments to the script or function you're in. For example, running a script named foo as ./foo bar baz would result in $1 == bar$2 == baz


Source: parameters - What does -n mean in Bash? - Stack Overflow

Wednesday, November 30, 2022

Make a duplicate copy of a specified file using bash shell script

 #!/usr/bin/bash

#if [ $# -lt 2 ] || [ $#  -gt 2 ]

#if test $# -lt 2 -o  $#  -gt 2

#if [[ $# -lt 2 ]] || [[  $#  -gt 2 ]]

if  (($# < 2)) || ((  $#  > 2 ))


then

echo invalid

exit

else

echo file to be copied : $1

echo new file name : $2

cp $1 $2

echo copy successful




fi

leap year program in bash shell script

#/usr/bin/bash

echo "Enter year"

read year

if [[ $(($year % 100)) -ne 0 ]]

#if (((year%100)!=0))

#if  [ $(($year % 100)) -ne 0 ]

then

if [ $(($year%4)) -eq 0 ]

then

echo "Leap Year"

else

echo "Not a leap year"

fi

else

if [ $(($year % 400)) -eq 0 ]

then

echo "Leap Year"

else

echo "Not a leap year"

fi

fi

Different ways to implement numerical comparisons using if else in bash

 #!/usr/bin/bash
echo "enter a number"
read num
if [[ $num -ge 1 ]] && [[ $num -lt 10 ]]
then
echo "A"
elif [[ $num -ge 10 ]] && [[ $num -lt 90 ]]
then
echo "B"
elif [[ $num -ge 90 ]] && [[ $num -lt 100 ]]
then
echo "C"
else
echo "D"
fi


#!/bin/bash
echo "enter a number"
read num
if (( num >= 1)) && ((num<10))
then
echo "sam"
elif ((num >= 10)) && ((num < 90 ))

then
echo "ram"
elif ((num >= 90)) && ((num  <100))
then
echo "rahim"
else
echo "tara"
fi

#!/bin/bash
echo "enter a number"
read num
if [ $num -ge 1 ] && [ $num -lt 10 ]
then
echo "A"
elif [ $num -ge 10 ] && [ $num -lt 90 ]
then
echo "B"
elif [ $num -ge 90 ] && [ $num -lt 100 ]
then
echo "C"
else
echo "D"
fi



Monday, November 28, 2022

Matching username from input with /etc/passwd without grep

 #/bin/bash

echo "enter username to check"

read username

match=0

for line in `cat /etc/passwd`

do


if test `echo $line | cut -d ":" -f 1| cut -d "," -f 1` == $username ;

then

#match=$(($match+1))

#let "match=match+1"

#let "match++"

((match++))

fi


done

if [ $match -gt 0 ];

then

echo "$username is valid because match is $match"

else

echo "$username is not valid because match is $match"

fi

Sunday, November 27, 2022

Get length of a string in bash shell script

#!/bin/bash

# Create a new string

mystring="lets count the length of this string"

i=${#mystring}

echo "Length: $i"


Source:https://www.hostinger.in/tutorials/bash-script-example

If else example in bash shell script,explanation on the difference ofusage of no bracket and single bracket after if

 #!/bin/bash

salary=1000

expenses=800

#Check if salary and expenses are equal

if test  $salary == $expenses ;

then

    echo "Salary and expenses are equal"

#Check if salary and expenses are not equal

elif test  $salary != $expenses ;

then

    echo "Salary and expenses are not equal"

fi



Now if we omit the single bracket [ after if we will encounter an error,the explanation is given below

[ is actually a command, equivalent (almost, see below) to the test command. It's not part of the shell syntax. (Both [ and test, depending on the shell, are often built-in commands as well, but that doesn't affect their behavior, except perhaps for performance.)

An if statement executes a command and executes the then part if the command succeeds, or the else part (if any) if it fails. (A command succeeds if it exits with a status ($?) of 0, fails if it exits with a non-zero status.)

In

if [ "$name" = 'Bob' ]; then ...

the command is

[ "$name" = 'Bob' ]

(You could execute that same command directly, without the if.)

In

if grep -q "$text" $file ; then ...

the command is

grep -q "$text" $file

man [ or man test for more information.

FOOTNOTE: Well, the [ command is almost equivalent to the test command. The difference is that [ requires ] as its last argument, and test does not -- and in fact doesn't allow it (more precisely, test doesn't treat a ] argument specially; for example it could be a valid file name). (It didn't have to be implemented that way, but a [ without a matching ] would have made a lot of people very very nervous.)


Source:https://stackoverflow.com/questions/8934012/when-are-square-brackets-required-in-a-bash-if-statement

Array example in bash shell script

 #!/bin/bash

# Create an indexed array

IndexedArray=(egg burger milk)

#Iterate over the array to get all the values

for i in "${IndexedArray[@]}";do echo "$i";done


Source:https://www.hostinger.in/tutorials/bash-script-example

Thursday, November 24, 2022

Create a file and write something to it using perl

 use strict;

use warnings;

$|=1;

sub main{

my $output='output.txt';

open(OUTPUT,'>'.$output)or die "Can't create $output.\n";

print OUTPUT "Hello\n";

close(OUTPUT);

}

main();


Read lines from a text file and print those lines based on condition using perl

 use strict;

use warnings;

#disabling output buffering

$|=1;


sub main{

#my @files=('./a.txt','./b.txt','./c.txt',);

my $file='./a.txt';

open(INPUT,$file) or die("Input file $file not found.\n");

while(my $line=<INPUT>)

{

if($line=~/abc/)

{


print $line;

}

}

close(INPUT);

}

main();


Check the existence of multiple files using array in perl

                                          

 use strict;

use warnings;

#disabling output buffering

$|=1;


sub main{

my @files=('./a.txt','./b.txt','./c.txt',);

#my $file='./a.txt';

foreach my $file(@files){

print "$file\n";


if(-f $file)

{

print "$file exists\n";


}

else

{


print "$file does not exist\n";


}

}

}

main();


else

{


print "$file does not exist\n";


}

}

}

main();

Check if a file exists using perl

 use strict;

use warnings;

sub main{

my $file='./a.txt';

if(-f $file)

{

print "$file exists\n";


}

else

{


print "$file does not exist\n";


}

}

main();

Find the files created in the guest machine in windows subsystem in linux (WSL2)

 In the guest terminal 

just enter:

explorer.exe .
 
Source:https://superuser.com/questions/1185033/what-is-the-home-directory-on-windows-subsystem-for-linux 

Check if an username is present in /etc/passwd using shell script

 #!/bin/bash
read -rep $'Please enter username\n' username
#echo "you have entered $username"
if [ `grep -c $username /etc/passwd` -eq 0 ]
then
echo "$username is invalid"
else
echo "$username is valid"
fi

Wednesday, November 23, 2022

Storing the source code of a webpage in a variable using lwp and perl

use strict;
use warnings;
use LWP::Simple;
sub main{
print "Downloading ... \n";
#print get("http://www.google.com/");
#getstore("http://www.google.com","./source.code.html");
#to receive the response just as string we need to use single quote
#getstore('https://en.wikipedia.org/wiki/Main_Page#/media/File:Kathryn_Sullivan,_PCAST_Member_(cropped).jpg','face.jpg'>
my $code=getstore('https://en.wikipedia.org/wiki/Main_Page#/media/File:Kathryn_Sullivan,_PCAST_Member_(cropped).jpg','f>if($code==200)
{
print "Success\n";
}
else{
print "Failed\n";
}


print "Finished\n";
}
main();

Downloading and storing the source code of a web page in a file using lwp and perl

 use strict;
use warnings;
use LWP::Simple;
sub main{
print "Downloading ... \n";
#print get("http://www.google.com/");
getstore("http://www.google.com","./source.code.html");

print "Finished\n";
}
main();

Downloading and printing html css code of a page using perl and lwp

 use strict;
use warnings;
use LWP::Simple;
sub main{
print "Downloading ... \n";
print get("http://www.google.com/");
print "Finished\n";
}
main();

Tuesday, November 22, 2022

Newline character inside read in bash

 

read -rep $'Please Enter a Message:\n' message

Find size of individual files of a particular extension in bash

 echo "enter extension"
read ext
for i in `find . -name "*.$ext" -type f`; do
   # echo "$i"
   echo `du -k "$i" | cut -f1`
done

Find files of a particular extension in bash

 echo "enter extension"
read ext
for i in `find . -name "*.$ext" -type f`; do
    echo "$i"
done

Find total size of files of an extension given as input in bash

 #!/bin/bash
echo "Please enter extension"
read ext
total=0
for i in $(pwd)/*.$ext

do

#filesize=$((`stat --printf="%s" $i`))
#filesize=$((`wc -c $i | awk '{print $1}'))
filesize=$((`wc -c $i | cut -d " " -f 1`))
total=$(($total+$filesize))
done

echo "The total size of $ext files in present directory is $total"

#alternate way


#!/usr/bin/bash
read -rep $'Please enter the extension\n' ext
total=0
for i in `ls`
do
if [[ "$i" == *"$ext"* ]]
then
#echo $i
total=$(($total + `du -k $i | cut -f 1`))
fi
done
echo "The total size of $ext files is $total"







Thursday, November 17, 2022

Some bash keyboard shortcuts and special characters

Some bash keyboard shortcuts


  • Esc + T: Swap the last two words before the cursor
  • Ctrl + H: Delete the letter starting at the cursor
  • Ctrl + W: Delete the word starting at the cursor
  • TAB: Auto-complete files, directory, command names and much more
  • Ctrl + R: To see the command history.
  • Ctrl + U: Clear the line
  • Ctrl + C: Cancel currently running commands.
  • Ctrl + L: Clear the screen
  • Ctrl + T: Swap the last two characters before the cursor

Some bash special characters

Characters Description
/ Directory separator, used to separate a string of directory names. Example: /home/projects/file
\ Escape character. If you want to reference a special character, you must “escape” it with a backslash first. Example: \n means newline; \v means vertical tab; \r means return
# Lines starting with # will not be executed. These lines are comments
. Current directory. When its the first character in a filename, it can also “hide” files
.. Returns the parent directory
~ Returns user’s home directory
~+ Returns the current working directory. It corresponds to the $PWD internal variable
~- Returns the previous working directory. It corresponds to the $OLDPWD internal variable
* Represents 0 or more characters in a filename, or by itself, it matches all files in a directory. Example: file*2019 can return: file2019, file_comp2019, fileMay2019
[] Can be used to represent a range of values, e.g. [0-9], [A-Z], etc. Example: file[3-5].txt represents file3.txt, file4.txt, file5.txt
| Known as “pipe". It redirects the output of the previous command into the input of the next command. Example: ls | less
< It redirects a file as an input to a program. Example: more < file.txt
> In script name >filename it will redirect the output of “script name” to “file filename”. Overwrite filename if it already exists. Example: ls > file.txt
>> Redirect and append the output of the command to the end of the file. Example: echo "To the end of file" >> file.txt
& Execute a job in the background and immediately get your shell back. Example: sleep 10 &
&& “AND logical operator”. It returns (success) only if both the linked test conditions are true. It would run the second command only if the first one ran without errors. Example: let "num = (( 0 && 1 ))"; cd/comp/projs && less messages
; “Command separator”. Allows you to execute multiple commands in a single line. Example: cd/comp/projs ; less messages
? This character serves as a single character in a filename. Example: file?.txt can represent file1.txt, file2.txt, file3.txt

 

Wednesday, November 16, 2022

Some loop examples in bash scripting for and while

 
for i in  1 2 3 4 5
do
echo "Maharshi"
done

for i in  {0..10..5}
do
echo -e "Maharshi\t$i"
done

for i in  {10..0..-5}
do
echo -e "Maharshi\t$i"
done

for i in {1..10}
do
printf "%s\n%s\n" "Galgotias" "UNiversity";
done


for i in $(seq 1 10)
do
printf "%s\n%s\n" "Galgotias" "UNiversity";
done


for i in $(seq 1 2 10)
do
printf "i is %d\n" "$i";
done

for i in $(seq 10 -2 1)
do
printf "i is %d\n" "$i";
done

for((i=4;i<10;i++))
do
echo "Maharshi";
done

echo "enter a number";
read number;
if (((number < 10))  &&  ((number > 1)))||(((number<100))&&((number>90)))
then
echo $number;
fi

i=0
while ((i < 5 ))
do
echo "maharshi";
i=$(($i+1));
done

arithmatic expansion

i=15;
i=$(($i*5));
echo $i;

Digonal number pattern in bash solved

  printf "Enter row number";
    read n;
    c=1
    for((i=1;i<=(n-1);i++))
    {
   
        for((j=1;j<=(n-1);j++))
        {
            if(((i==j)||(j==(n-i))))
            then
            printf $c ;
            else
            printf " ";
            fi
        }
        if ((c>=4))
        then
        ((c=c-1));
        else
        ((c=c+1));
        fi
        printf "\n";
    }

 

 


Monday, November 14, 2022

Set up cgi-perl in Debian 11

apt-get install apache2

/sbin/a2enmod cgid


systemctl restart apache2


cd /usr/lib/cgi-bin


nano /usr/lib/cgi-bin/test.pl


#!/usr/bin/perl

print "Content-Type: text/html\n\n";

print ("<h1>Perl is working!</h1>");

chmod 755 /usr/lib/cgi-bin/test.pl

http://172.31.8.195/cgi-bin/test.pl


Source: https://techexpert.tips/apache/perl-cgi-apache/

Some bash shell script examples for beginners

 even odd


echo "Please enter a number"
read num
if [ `expr $num % 2`  == 0 ]
then
echo "$num is even"
else
echo "$num is odd"
fi


largest of three numbers

echo "please enter 3 numbers"
read num1
read num2
read num3

if test $num1 -gt $num2 -a $num1 -gt $num3
then
echo "$num1 is the greatest"
elif test $num2 -gt $num3
then
echo "$num2 is the greatest"
else
echo "$num3 is the greatest"
fi


calculate net salary


echo "enter basic salary"
read bs
hra=`echo $bs*10/100 | bc`
ta=`echo $bs*15/100 | bc`
da=`echo $bs*2/100 | bc`
pf=`echo $bs*10/100 | bc`
tax=`echo $bs*5/100 | bc`

netsal=`echo $bs+$hra+$ta+$da-$pf-$tax | bc`
echo "net salary is $netsal"


calculate conditional discount and tax


echo  "please enter the amount that you want to buy"
read amount
if test  $amount -lt 1000
then
tax=`echo $amount \* 2/100 | bc`
discount=`echo $amount \* 10/100 | bc`
else
tax=`echo $amount \* 5/100 | bc`
discount=`echo $amount \* 20/100 | bc`
fi

totalcost=`echo $amount - $tax + $discount | bc`
echo  "total cost is $totalcost"


Sunday, October 30, 2022

Perl loop assignment solved

 In this exercise, you will need to loop through and print out all even numbers from the @NUMBERS array in the same order they are received. Don't print any numbers that come after 237 in the array.

 

@NUMBERS = (951,402,984,651,360,69,408,319,601,485,980,507,725,547,544,615,83,165,141,501,263,617,865,575,219,390,237,412,566,826,248,866,950,626,949,687,217,815,67,104,58,512,24,892,894,767,553,81,379,843,831,445,742,717,958,609,842,451,688,753,854,685,93,857,440,380,126,721,328,753,470,743,527);


for($i=0;($i<=$#NUMBERS);$i+=1) {
if ($NUMBERS[$i]==237)
{
last;
}
if ($NUMBERS[$i]%2==0)
{
print $NUMBERS[$i]."\n";
}


Perl way


@NUMBERS = (951,402,984,651,360,69,408,319,601,485,980,507,725,547,544,615,83,165,141,501,263,617,865,575,219,390,237,412,566,826,248,866,950,626,949,687,217,815,67,104,58,512,24,892,894,767,553,81,379,843,831,445,742,717,958,609,842,451,688,753,854,685,93,857,440,380,126,721,328,753,470,743,527);

foreach $number (@NUMBERS) {
    if ($number % 2 == 0) {
        print $number . "\n";
    }
    last if ($number == 237);
}

Perl Assignment solved using array and hash

 An array @family holds a list of family member names. The first hash %shoe_color contains favorite shoe color per person name. The second hash %shoe_size contains shoe size per person name.

Evaluate and print the favorite shoe color and shoe size per each family member. For shoe sizes 10 and above, add the word 'large' to the output line.

Output lines should be in the format: "Homer wears large brown shoes size 12".

Note: not all family members may be included in the hash variables, so you better conditionally check if they exist or not (using the exists operator). If a name does not exist, add the key/value pair into the hash variables - for show color add: black; for shoe size add 99.

Solution

@family = ('Homer', 'Moe', 'Maggie');
%shoe_color = ('Lisa' => 'red', 'Homer' => 'brown', 'Maggie' => 'pink', 'Marge' => 'blue', 'Bart' => 'yellow');
%shoe_size = ('Moe' => 9, 'Lisa' => 7, 'Homer' => 12, 'Bart' => 8, 'Maggie' => 4);

$default_shoe_color = "black";
$default_shoe_size = 4;

$member = $family[0];
if (!exists $shoe_color{$member}) {
    $shoe_color{$member} = $default_shoe_color;
}
if (!exists $shoe_size{$member}) {
    $shoe_size{$member} = $default_shoe_size;
}
$is_large = ($shoe_size{$member} >= 10) ? " large " : " ";
print "$member wears$is_large$shoe_color{$member} shoes size $shoe_size{$member}\n";

$member = $family[1];
if (!exists $shoe_color{$member}) {
    $shoe_color{$member} = $default_shoe_color;
}
if (!exists $shoe_size{$member}) {
    $shoe_size{$member} = $default_shoe_size;
}
$is_large = ($shoe_size{$member} >= 10) ? " large " : " ";
print "$member wears$is_large$shoe_color{$member} shoes size $shoe_size{$member}\n";

$member = $family[2];
if (!exists $shoe_color{$member}) {
    $shoe_color{$member} = $default_shoe_color;
}
if (!exists $shoe_size{$member}) {
    $shoe_size{$member} = $default_shoe_size;
}
$is_large = ($shoe_size{$member} >= 10) ? " large " : " ";
print "$member wears$is_large$shoe_color{$member} shoes size $shoe_size{$member}\n";

Perl assignment solved using array and hash

 Assign the hash variable called car_catalog to include the following car models and their showroom prices in dollars. Use the car model name as the hash key. The cars and prices are:

    Model: BMW Series 5, price: 100000
    Model: Mercedes 2000, price: 250000
    Model: Toyota Corolla, price: 20000
    Model: Lexus 3, price: 95000

Assign an array variable called my_wishlist with the two cars you want to buy: the first array element is the full model name of the BMW car and the second array model is the full model name of the Toyota car. Use the array variable contents as keys to the hash variable in order to print lines in the following format: "I would like to buy one for the price of Dollars."

Solution

%car_catalog = ("BMW Series 5" => 100000 , "Mercedes 2000" => 250000, "Toyota Corolla" => 20000,"Lexus 3"=>95000);
@my_wishlist = ("BMW Series 5","Toyota Corolla");
print "I would like to buy one $my_wishlist[0] for the price of $car_catalog{$my_wishlist[0]} Dollars.\n";
print "I would like to buy one $my_wishlist[1] for the price of $car_catalog{$my_wishlist[1]} Dollars.\n";

 

 

Source:https://www.learn-perl.org/en/Variables_and_Types

Array and hash example in perl

 @item_price_list = (5 , 8 , 24);
@item_name_list = ("Apple", "Banana", "Mushroom");
print "The price of one $item_name_list[0] is $item_price_list[0] gold coins.\n";
print "The price of one $item_name_list[1] is $item_price_list[1] gold coins.\n";
print "The price of one $item_name_list[2] is $item_price_list[2] gold coins.\n";


%item_catalog = ("Apple" => 5 , "Banana" => 8, "Mushroom" => 24);
# note the required backslash to escape the double-quotes around the key string Apple
print "The price of one Apple is $item_catalog{\"Apple\"} gold coins.\n";
$item_name = "Banana";
print "The price of one $item_name is $item_catalog{$item_name} gold coins.\n";
@item_name_list = ("Apple", "Banana", "Mushroom");
print "The price of one $item_name_list[2] is $item_catalog{$item_name_list[2]} gold coins.\n";


Friday, October 21, 2022

Calculate the area of a right angle triangle using a package in perl

 

package Triangle;   # class name

sub new {
  my $class = shift;
  my $self = {
      _length => shift,
      _height => shift,
  };

 

  # Print all the values just for clarification.
  print "Length is $self->{_length}\n";
  print "Height is $self->{_height}\n";
  bless $self, $class;
  return $self;
}

sub area{
    my ($self) = @_;
    return ($self->{_length} * $self->{_height}) / 2;
  }

1;

$object = new Triangle( 4, 5);
print "Area of Triangle: " . $object->area();

Thursday, October 20, 2022

Sorting array of numbers in perl

 

@numbers = (13, 9, 22, 27, 1, 3, -4, 10);
print "Original: @numbers\n\n";

@sorted_numbers = sort { $a <=> $b } @numbers;

print "After sorting: @sorted_numbers";

Sorting array of strings in perl

 

#defining and array
@fruits = ('Rasberry', 'Orange', 'Apricot','Banana', 'Apple','Olive' );

@fruits = sort(@fruits); #applying the sort function
print("@fruits"); #printing the sorted array

matrix assignment in perl

 sub printMat {
  #write the code for making and printing the matrix here
  #use can use \n to move numers to next line in the matrix
  #use " " to add space between numbers in matrix
  #print "Write your code below"; #comment out this line when you start writing cod
  for ($i = 0; $i < 4 ; $i++) {
    for ($j = 0; $j < 4; $j++) {
      if ($i==$j)
      {
        $val=0;
      }
      elsif($j<$i)
      {
        $val=-1;
      }
      else{
        $val=1;
      }
       $comparisonAdjectives[$i][$j] = $val;

    }
  }

  for ($i = 0; $i < 4 ; $i++) {
    for ($j = 0; $j < 4; $j++) {
      if ($comparisonAdjectives[$i][$j]>=0){
          print " ".$comparisonAdjectives[$i][$j]." ";
      }
      else
      {
          print $comparisonAdjectives[$i][$j]." ";
      }
      
    }
    print "\n";
  }
}

printMat();

Multidimensional array in perl

 

@comparisonAdjectives= (["good", "better", "best"],
                        ["bad", "worse", "worst"],
                        ["tall", "taller", "tallest"]);

for ($i = 0; $i < 3 ; $i++) {
    for ($j = 0; $j < 3; $j++) {
        print $comparisonAdjectives[$i][$j] . " ";
    }
    print "\n";
}

Find maximum value from an array using perl

 

 #Returns maximum value from Array passed as parameter
  sub Find_Maximum {

  my @list = @_;

  $max = $list[0];

  for ($i = 1; $i <= $#list; $i++) { #iterate over all the array elements

    if ($list[$i] > $max) {                 #check if current element is greater than the already
      #stored max value
      $max = $list[$i];                     # if yes then update the max value to current element
    }
  }
  return $max;                           #return the maximum value
}#end of Find_Maximum()

@array = (15, 6, 3, 21, 19, 4);
print Find_Maximum (@array);