Replicate the array number of times in Perl - arrays

I have array which contains 5 elements (1,2,3,4,5). I want to replicate this a number of times based on the value set in the scalar $no_of_replication, e.g. 3.
So that my final array would contain (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5).
Here is what I have tried. It gives me scalar content instead of elements.
use strict;
use warnings;
use Data::Dumper;
my #array = (1,2,3,4,5);
print Dumper(\#array);
my $no_of_replication = 3;
my #new_array = #array * $no_of_replication;
print Dumper(\#new_array);
My array(#new_array) should be like (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5).

The operator for that is x and you need to be careful with the array syntax:
#new_array = ( #array ) x $no_of_replication;
Found the solution here:
Multiplying strings and lists in perl via Archive.org

Related

How to access Array Item With Variable perl?

I'm new to perl.
I'm facing a problem to access items in array by variable like other languages eg. C C++ Python3 JavaScript
Expected Way To Do Same In Perl:
print "#array[$var]" ;
It should print value of array at $var.
But It Gives Error. Any other way To do same.
To access the value of an element of array #array, one uses $array[$i].
This is documented in perldata.
And yes, $array[$i] can be used in double-quoted string literals.
print("$array[$i]\n");
Note that #array[$i] also works, but with a warning. You should only use #array[...] when there's the possibility of getting multiple elements.
$ perl -e'
use strict;
use warnings;
my #array = "a".."z";
my $var = 2;
print "#array[$var]\n";
'
Scalar value #array[...] better written as $array[...] at -e line 7.
c
$ perl -e'
use strict;
use warnings;
my #array = "a".."z";
print "#array[2..4]\n";
'
c d e
Try this: $array[$var]. What you wrote before was an incorrect way to access an array slice. If you need a slice, try this: #array[$foo..$bar].

Extract number from array in Perl

I have a array which have certain elements. Each element have two char "BC" followed by a number
e.g - "BC6"
I want to extract the number which is present and store in a different array.
use strict;
use warnings;
use Scalar::Util qw(looks_like_number);
my #band = ("BC1", "BC3");
foreach my $elem(#band)
{
my #chars = split("", $elem);
foreach my $ele (#chars) {
looks_like_number($ele) ? 'push #band_array, $ele' : '';
}
}
After execution #band_array should contain (1,3)
Can someone please tell what I'm doing wrong? I am new to perl and still learning
To do this with a regular expression, you need a very simple pattern. /BC(\d)/ should be enough. The BC is literal. The () are a capture group. They save the match inside into a variable. The first group relates to $1 in Perl. The \d is a character group for digits. That's 0-9 (and others, but that's not relevant here).
In your program, it would look like this.
use strict;
use warnings;
use Data::Dumper;
my #band = ('BC1', 'BC2');
my #numbers;
foreach my $elem (#band) {
if ($elem =~ m/BC(\d)/) {
push #numbers, $1;
}
}
print Dumper #numbers;
This program prints:
$VAR1 = '1';
$VAR2 = '2';
Note that your code had several syntax errors. The main one is that you were using #band = [ ... ], which gives you an array that contains one array reference. But your program assumed there were strings in that array.
Just incase your naming contains characters other than BC this will exctract all numeric values from your list.
use strict;
use warnings;
my #band = ("AB1", "BC2", "CD3");
foreach my $str(#band) {
$str =~ s/[^0-9]//g;
print $str;
}
First, your array is an anonymous array reference; use () for a regular array.
Then, i would use grep to filter out the values into a new array
use strict;
use warnings;
my #band = ("BC1", "BC3");
my #band_array = grep {s/BC(\d+)/$1/} #band;
$"=" , "; # make printing of array nicer
print "#band_array\n"; # print array
grep works by passing each element of an array in the code in { } , just like a sub routine. $_ for each value in the array is passed. If the code returns true then the value of $_ after the passing placed in the new array.
In this case the s/// regex returns true if a substitution is made e.g., the regex must match. Here is link for more info on grep

use edit distance on arrays in perl

I am attempting to compare the edit distance between two arrays. I have tried using Text:Levenshtein.
#!/usr/bin/perl -w
use strict;
use Text::Levenshtein qw(distance);
my #words = qw(four foo bar);
my #list = qw(foo fear);
my #distances = distance(#list, #words);
print "#distances\n";
#results: 3 2 0 3
I however want the results to appear as follows:
2 0 3
2 3 2
Taking the first element of #list through the array of #words and doing the same through out the rest of the elements of #list.
I plan on upscaling this to a much larger arrays.
I'm not sure to understand exactly what you meant, but I think this is what you expect :
#!/usr/bin/perl -w
use strict;
use Text::Levenshtein qw(distance);
my #words = qw(four foo bar);
my #list = qw(foo fear);
foreach my $word (#list) {
my #distances = distance($word, #words);
print "#distances\n";
}
Taking the first element of #list through the array of #words and doing the same through out the rest of the elements of #list.
You just described exactly what you need to do to get the output you would like; loop through the #list array and for each element compute the distance for all elements of the #words array.

Perl array element comparing

I am new in Perl programming. I am trying to compare the two arrays each element. So here is my code:
#!/usr/bin/perl
use strict;
use warnings;
use v5.10.1;
my #x = ("tom","john","michell");
my #y = ("tom","john","michell","robert","ricky");
if (#x ~~ #y)
{
say "elements matched";
}
else
{
say "no elements matched";
}
When I run this I get the output
no elements matched
So I want to compare both array elements in deep and the element do not matches, those elements I want to store it in a new array. As I can now compare the only matched elements but I can't store it in a new array.
How can I store those unmatched elements in a new array?
Please someone can help me and advice.
I'd avoid smart matching in Perl - e.g. see here
If you're trying to compare the contents of $y[0] with $x[0] then this is one way to go, which puts all non-matches in an new array #keep:
use strict;
use warnings;
use feature qw/say/;
my #x = qw(tom john michell);
my #y = qw(tom john michell robert ricky);
my #keep;
for (my $i = 0; $i <$#y; $i++) {
unless ($y[$i] eq $x[$i]){
push #keep, $y[$i];
}
}
say for #keep;
Or, if you simply want to see if one name exists in the other array (and aren't interested in directly comparing elements), use two hashes:
my (%x, %y);
$x{$_}++ for #x;
$y{$_}++ for #y;
foreach (keys %y){
say if not exists $x{$_};
}
It would be well worth your while spending some time reading the Perl FAQ.
Perl FAQ 4 concerns Data Manipulation and includes the following question and answer:
How do I compute the difference of two arrays? How do I compute
the intersection of two arrays?
Use a hash. Here's code to do both and more. It assumes that each
element is unique in a given array:
my (#union, #intersection, #difference);
my %count = ();
foreach my $element (#array1, #array2) { $count{$element}++ }
foreach my $element (keys %count) {
push #union, $element;
push #{ $count{$element} > 1 ? \#intersection : \#difference }, $element;
}
Note that this is the symmetric difference, that is, all elements
in either A or in B but not in both. Think of it as an xor
operation.

Sorting Arrays in Perl?

I am getting an error while trying to sort a simple array...
The ERROR reads: "use of uninitialized value in numeric comparison (<=>) at file.pl line #"
#!/usr/bin/perl
use strict
use wardings
use Data::Dumper
my #array
my $array
$array[1]= 5
$array[2]= 2
$array[3]= 3
$array[4]= 4
$array[5]= 1
sub numerically {$a <=> $b}
my #sortedarray = sort numerically #array;
print "#sortedarray\n";
I am just trying to sort the array to get:
1 2 3 4 5
I am new at perl so this might just be something stupid, but please help me... Thanks
Arrays are indexed starting at 0. The error comes from trying to sort the array when $array[0] is undefined.
Update: Also, in perl, one would write:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my #array = qw(1 2 3 4 5);
sub numerically {$a <=> $b}
my #sortedarray = sort numerically #array;
print "#sortedarray\n";
There is no point in declaring $array -- that would be a scalar. You are only working with the array #array, even though it is called with a $. Please read the perl documentation.
first of all, you need a semi-colon at the end of every statement. second, you're not using Data::Dumper, so why do you include it? You also don't need to declare the sub:
#!/usr/bin/env perl
use strict;
use warnings;
my #sorted = sort {$a <=> $b} qw (4 2 3 1 5);
print "#sorted\n";
And there we have it.
You're missing a shedload of semicolons.
It's warnings, not wardings.
Element 0 in your array is undefined.

Resources