Friday 19 March 2021

perl data structures tutorial - part1

Perl provides a rich set of data structures that can be used to store and manipulate data. In this tutorial, I'll cover the most commonly used data structures in Perl, along with code examples.

Arrays

Arrays are ordered lists of scalar values. To declare an array, you use the @ symbol followed by the array name. Here's an example:

@my_array = (1, 2, 3, 4, 5);


You can access individual elements of the array using the array name followed by the index of the element in square brackets. Here's an example:

print $my_array[0]; # prints 1


You can also use the scalar function to get the number of elements in an array:

print scalar(@my_array); # prints 5


Read more »

Labels:

Monday 4 November 2019

perl read file - 15 ways

Method 1:


open(FH,'<file.txt') or die "Cant open file $!";

print FH;

close(FH);

Read more »

Labels:

Wednesday 23 October 2019

place and plays $_ in perl?

Method 1:


while(<>)
{
    print;
}

Method 2:


for ('l','s','h','c','g')
{
   print;
   print "\n";
}

Method 3:

@a=split //,'hello';

Method 4:


$_="hello";
$_=~s/he/she/g;

print $_;

Method 5:


$_="he l lo";
for (split)
{
   print;
   print "\n";
}

Method 6:


$_='perlbot';

print if /p/;

Method 7:

foreach ('l','s','h','c','g')
{
   print;
   print "\n";
}

Method 8:


$_ = "prlbot";

print /perl/ ?'perlbot':'normalbot',"\n";

Method 9:


$_="perl";
$_=~tr/p/P/;

print $_;

Method 10:


@a=('l','s','h','c','g');

print grep $_,@a;

Method 11:


@a=('l','s','h','c','g');

print map $_,@a;

Method 12:


%hash=(1,2,7,4,9,6);

while (each %hash) {

 print "$_=$hash{$_}\n";

    }

Method 13:


opendir($_,"/tmp") || die "Can't open dir $!";

@array =readdir($_);

closedir $_;

print @array;

Method 14:

while(<>)
{
    chomp($_);
     print $_;
}

Method 15:


while(<>)
{
    chop($_);
    print $_;
}

Method 16:


while(<>)
{
   chomp($_);
   $output = eval $_;
   print $output;
}

Method 17:


$_="he l lo";

print length($_);

Method 18:


$_="he l k lo";
$v=reverse $_;

print $v;

Method 19:


$_ = 9.0;

print exp $_;

Method 20:


$_ = "10";

print hex $_;

Method 21:


$_ = "Hello Perl Bot";

print index $_, 'Perl';

Method 22:


$_="he l k lo";
$v=lc $_;

print $v;

Method 23:


$_="he l k lo";
$v=uc $_;

print $v;

Method 24:


$_="he l k lo";
$v=ucfirst $_;

print $v;

Method 25:


$_="he l k lo";
$v=lcfirst $_;

print $v;

Method 26:


$_ = "144";

print sqrt $_;

Method 27:


$_ = "Hello Perl Bot Perl";

print rindex $_, 'Perl';

Method 28:


while(($_ = getc) eq 'yes')
{
   print $_;
}

Method 29:


$_ = "Hello Perl Bot Perl";

if (defined $_) {
    print "$_ is defined";
}

Method 30:

$_ = "Hello Perl Bot Perl";

print $_;

Tuesday 1 October 2019

hash-inversion-by-reversing-the-values-to-keys-and-keys-to-values-in-perl


Method 1:

                             %hash=(9,5,2,1,4,6);
                             @final5{values %hash} = keys %hash;
                              print @final5;


Method 2:

                              $z=0;
                              %hash=(9,5,2,1,7,6);
                              foreach((sort values %hash)) {
                              $final5{ $_ } = (sort keys %hash)[$z];
                              $z++;
                              }


Method 3:

                                %hash=(9,5,2,1,4,6);

                                @first1=values %hash;
                                @second2=keys %hash;
                                foreach my $a1 (@first1)
                                {
                                        my $a2= shift @second2;
                                       $final3{ $a1 } = $a2;
                                 }


Method 4:

                               %hash=(9,5,2,1,4,6);
                               @first=values %hash;
                               @second=keys %hash;
                               for($j = 0; $j < @first; $j++)
                               {
                                         $final{$first[$j]} = $second[$j];
                               }


Method 5:

                                %hash=(9,5,6,1);
                               @first_1=values %hash;
                               @second_1=keys %hash;
                               while( @first_1 || @second_1)
                              {
                                      my $a1= shift @first_1 || "Perl_Methods_Master";
                                      my $a2= shift @second_1 || "Perl_Methods_Master";
                                      $final{$a1} = $a2;
                               }



Method 6:

                                %hash=(9,5,2,1,4,6);
                               @first1=values %hash;
                               @second2=keys %hash;
                               while( @first1 && @second2)
                              {
                                      my $b1= shift @first1;
                                      my $b2= shift @second2;
                                      $final{$b1} = $b2;
                               }



Method 7:

                               %hash=(9,5,2,1,4,6);
                               @first2=values %hash;
                                @second1=keys %hash;
                               while (@first2 || @second1)
                               {
                                           $final{shift @first2} = shift @second1;
                                }


Method  8:

                               %hash=(9,5,2,1,4,6);
                               @first1=values %hash;
                               @second1=keys %hash;
                               $final{shift @first1}=shift(@second1) while @second1;



Method 9:

                             %final1=(9,5,2,1,4,6);
                             @first2=values %final1;
                             @second2=keys %final1;
                              $i=0;
                             %final2=map {$first[$i++],$_; } @second2;



Method 10:

                             %final5=(9,5,2,1,4,6);
                              while (($k, $v) = each %final5)
                             {
                                        $final2{$v}=$k;
                              }



Method 11: 
                   
                              %final5=(9,5,2,1,4,6);
                              %final5 = reverse %final5;

                      .

Labels: ,

Monday 30 September 2019

How to assign more than one arrays to crate a complete hash in perl?


Method 1[Faster]:


                     %final=();
                    @first=(7,8,3,4);
                     @second=('a','s','d','f');
                     my %final;
                    @final{@first} = @second;
                     print %final;
Read more »

Labels: , , , , , ,

Friday 5 August 2022

Given the input string 'hello boss!,where are you?,"how, are you!",hi,"di chellam","welcome"' our objective is to design a Perl program that intelligently separates and extracts each individual word from the CSV-like structure. The complexity lies in correctly handling quoted content containing commas.

CODE:

use strict;
use warnings;
my $input_string = 'hello boss!,where are you?,"how, are you!",hi,"di chellam","welcome"';

# Initialize empty array to store extracted words
my @words = ();

# Use a while loop with a regex to extract words
while ($input_string =~ /((?:(?<=,)|^)\s*"[^"]*"\s*(?=,|$)|[^,]*),?/g) {
    my $word = $1;
    # Remove leading and trailing spaces
    $word =~ s/^\s+|\s+$//g;\
    # Check if the word is quoted

    if ($word =~ /^\"(.*)\"$/) {
        # Extract the word without the quotes
        my $quoted_word = $1;
        # Add the word to the array
        push @words, $quoted_word;
    } else {
        # Add the word to the array
        push @words, $word;
    }
}

# Print the extracted words
print join("\n", @words), "\n";
Read more »

Labels: ,

Monday 21 November 2022

Understanding Differences in Behavior of Process.join() in Windows 10 and Ubuntu 18.04 in Python 3.6

When it comes to multi-processing in Python, developers often run into differences in behavior between different operating systems. One such difference is in how Windows 10 and Ubuntu 18.04 handle the Process.join() function. In this article, we will explore this difference in behavior and understand what accounts for it.

Read more »

Labels: , ,

Wednesday 8 July 2020

perl program to Renaming Files with a Prefix

This Perl script renames all the files in the current directory with a given prefix. The prefix can be passed as a command-line argument.

Method 1: Using rename function

#!/usr/bin/perl

my $prefix = shift @ARGV || '';

opendir my $dh, '.' or die "Couldn't open current directory: $!";

while (my $filename = readdir $dh) {

    next if $filename =~ /^\./; # Skip dotfiles

    my $newname = $prefix . $filename;

    rename $filename, $newname or warn "Couldn't rename $filename: $!";

}

closedir $dh;


or


#!/usr/bin/perl

use strict;

use warnings;

use File::Glob;


my $prefix = 'new_';

my $pattern = '*.txt';


foreach my $file (glob $pattern) {

    my $new_file = $prefix . $file;

    rename $file, $new_file or die "Can't rename $file to $new_file: $!";

}

Save the script as rename.pl and run it with perl rename.pl newprefix_. This will add the prefix "newprefix_" to all the files in the current directory.


Method 2: Using File::Copy

This method uses the File::Copy module to copy files with a new name and then delete the old file. We can use the File::Glob module to get a list of files matching a pattern and then use the File::Copy module to copy each file with the new name.

#!/usr/bin/perl

use strict;

use warnings;

use File::Glob;

use File::Copy;

my $prefix = 'new_';

my $pattern = '*.txt';

foreach my $file (glob $pattern) {

    my $new_file = $prefix . $file;

    copy $file, $new_file or die "Can't copy $file to $new_file: $!";

    unlink $file or die "Can't delete $file: $!";

}

Save the script as rename_files_method2.pl and run it with perl rename_files_method2.pl. This will rename all .txt files in the current directory with the prefix new_.


Method 3: Using regular expressions

This method uses regular expressions to modify the filenames with a prefix. We can use the File::Glob module to get a list of files matching a pattern and then use regular expressions to modify each filename.

use strict;

use warnings;


use File::Glob;

my $prefix = 'new_';

my $pattern = '*.txt';

foreach my $file (glob $pattern) {

    my $new_file = $file;

    $new_file =~ s/^/$prefix/;

    rename $file, $new_file or die "Can't rename $file to $new_file: $!";

}

Save the script as rename_files_method3.pl and run it with `perl rename_files

all .txt files in the current directory with the prefix new_.


Method 4: Using File::Find

This method uses the File::Find module to recursively find and rename files with a prefix. The File::Find module provides a way to traverse a directory tree and apply a function to each file found. We can use the rename function within the wanted function to rename each file with the specified prefix.

#!/usr/bin/perl

use strict;

use warnings;

use File::Find;

my $prefix = 'new_';


sub rename_file {

    if (-f && /^.*\.txt$/) {

        my $new_file = $prefix . $_;

        rename $_, $new_file or warn "Can't rename $_ to $new_file: $!";

    }

}

find(\&rename_file, '.');

Save the script as rename_files_method4.pl and run it with perl rename_files_method4.pl. This will recursively find and rename all .txt files in the current directory and its subdirectories with the prefix new_.


Method 5: Using opendir and readdir

This method uses the opendir and readdir functions to find and rename files with a prefix. The opendir function opens a directory, and the readdir function reads the contents of the directory. We can use regular expressions to match the filenames and then use the rename function to rename each file with the specified prefix.

#!/usr/bin/perl

use strict;

use warnings;

my $prefix = 'new_';

opendir(my $dh, '.') or die "Can't open current directory: $!";

while (my $file = readdir($dh)) {

    next unless $file =~ /^.*\.txt$/;

    my $new_file = $prefix . $file;

    rename $file, $new_file or warn "Can't rename $file to $new_file: $!";

}

closedir $dh;

Save the script as rename_files_method5.pl and run it with perl rename_files_method5.pl. This will find and rename all .txt files in the current directory with the prefix new_.


Method 6: Using File::Copy

This method uses the File::Copy module to copy files with a prefix to a new directory and then rename the files. The File::Copy module provides functions for copying and moving files. We can use the copy function to copy the original files to a new directory with the prefix, and then use the rename function to rename the files with the specified prefix.

use strict;

use warnings;

use File::Copy;

my $prefix = 'new_';

my $new_dir = 'new_files';

mkdir $new_dir unless -d $new_dir;

opendir(my $dh, '.') or die "Can't open current directory: $!";

while (my $file = readdir($dh)) {

    next unless $file =~ /^.*\.txt$/;

    my $new_file = $prefix . $file;

    copy($file, "$new_dir/$new_file") or warn "Can't copy $file: $!";

}

closedir $dh;

opendir($dh, $new_dir) or die "Can't open $new_dir: $!";

while (my $file = readdir($dh)) {

    next unless $file =~ /^.*\.txt$/;

    my $new_file = $prefix . $file;

    rename("$new_dir/$file", "$new_dir/$new_file") or warn "Can't rename $file: $!";

}

closedir $dh;

Save the script as rename_files_method6.pl and run it with perl rename_files_method6.pl. This will copy all .txt files in the current directory to a new directory named new_files with the prefix new_, and then rename the files with the specified prefix.


Method 7: Using File::Find::Rule

This method uses the File::Find::Rule module to find and rename files with a prefix. The File::Find::Rule module provides a simple interface for finding files that match specified criteria. We can use the name method to match filenames and then use the rename function to rename each file with the specified prefix.

use strict;

use warnings;

use File::Find::Rule;

my $prefix = 'new_';

my @files = File::Find::Rule->file()->name('*.txt')->in('.');

foreach my $file (@files) {

    my $new_file = $prefix . $file;

    rename $file, $new_file or warn "Can't rename $file to $new_file: $!";

}

Save the script as rename_files_method7.pl and run it with perl rename_files_method7.pl. This will find and rename all .txt files in the current directory with the prefix new_.

Labels: