How to access Array Item With Variable perl? - arrays

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].

Related

Replicate the array number of times in Perl

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

Can't use string as an ARRAY ref while "strict refs"

I'm trying to dereference an array that is a value hash of a list element that is within an array so that I can manipulate and store it.
A sample of code is:
use strict;
use warnings;
my #array = qw(one two three four);
my #objects;
$objects[0]{"name"}="somestring";
$objects[0]{"value"}=#array;
print $objects[0]{"name"} . ": " . $objects[0]{"value"}[0];
print "\n";
When I try and run, I get:
Can't use string ("4") as an ARRAY ref while "strict refs" in use at
listarray.pl line 11.
Is there a way to do what I am intending (and use a foreach to iterate the inner and outer array)?
You should store the array as a reference:
$objects[0]{"value"} = \#array;
In your code, the #array was evaluated in scalar context, which returns the number of elements in the array (4).

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

Perl: string to an array reference?

Say, there is a string "[1,2,3,4,5]", how could I change it to an array reference as [1,2,3,4,5]? Using split and recomposing the array is one way, but it looks like there should be a simpler way.
eval is the simplest way
$string = "[1,2,3,4,5]";
$ref = eval $string;
but this is insecure if you don't have control over the contents of $string.
Your input string is also valid JSON, though, so you could say
use JSON;
$ref = decode_json( $string );
You can use eval but this should definitely be avoided when the string in question comes from untrusted sources.
Otherwise you have to parse it yourself:
my #arr = split(/\s*,\s*/, substr($string, 1, -1));
my $ref = \#arr;
You really should avoid eval if you can. If the string comes from outside the program then untold damage can be done by simply applying eval to it.
If the contents of the array is just numbers then you can use a regex to extract the information you need.
Here's an example
use strict;
use warnings;
my $string = "[1,2,3,4,5]";
my $data = [ $string =~ /\d+/g ];
use Data::Dump;
dd $data;
output
[1 .. 5]

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