Not able to print value using reference inside function in perl - perl

Why am i not being able to print the value using reference when its inside function?
sub fun {
$ref = #_;
print "\n Inside the function $ref->[1] \n";
}
my #arr=(2,3,4);
fun (\#arr);
my $ref2 = \#arr;
print "\n$ref2->[1]\n";
Output i get is :
Inside the function
3

It is your assignment that is wrong:
$ref = #_;
Because in scalar context, an array returns its size, not its elements. Scalar context is imposed when you have a scalar value on the left hand side. You should do:
my ($ref) = #_;
Or
my $ref = shift; # shifts first argument from #_
You also need to change $ref->[1] to $ref->[0], or you will refer to the wrong element. Perl arrays start at index 0.
What you should have done is to use
use strict;
use warnings;
Which would have given you the error:
Can't use string ("1") as an ARRAY ref while "strict refs" in use at line ...
Which is what happens. You assign the size 1 to $ref, and then try to use it as an array ref: $ref->[1]

Related

How do you lock a member variable in perl?

I wrote a script in perl which does multi-threading, I then tried to convert it over into an object. However, I can't seem to figure out how to lock on a member variable. The closest I've come to is:
#!/usr/bin/perl
package Y;
use warnings;
use strict;
use threads;
use threads::shared;
sub new
{
my $class = shift;
my $val :shared = 0;
my $self =
{
x => \$val
};
bless $self, $class;
is_shared($self->{x}) or die "nope";
return $self;
}
package MAIN;
use warnings;
use strict;
use threads;
use threads::shared;
use Data::Dumper;
my $x = new Y();
{
lock($x->{x});
}
print Dumper('0'); # prints: $VAR = '0';
print Dumper($x->{x}); # prints: $VAR = \'0';
print "yes\n" if ($x->{x} == 0); # prints nothing
#print "yes\n" if ($$x->{x} == 0); # dies with msg: Not a SCALAR reference
my $tmp = $x->{x}; # this works. Must be a order of precedence thing.
print "yes\n" if ($$tmp == 0); # prints: yes
#++$$x->{x}; # dies with msg: Not a SCALAR reference
++$$tmp;
print Dumper($x->{x}); # prints: $VAR = \'1';
This allows me to put a lock on the member var x, but it means I'd be needing 2 member variables as the actual member var isn't really capable of being manipulated by assigning to it, incrementing it, etc. I can't even test against it.
EDIT:
I'm thinking that I should rename this question "How do you dereference a member variable in perl?" as the problem seems to boil down to that. Using $$x->{x} is invalid syntax and you can't force precedence rules with parentheses. I.e. $($x->{x}) doesn't work. Using a temporary works but it a nuisance.
I don't get what you are trying to do with threads and locking, but there are some simple errors in the way you use references.
$x->{x}
is a reference to a scalar, so the expressions
$x->{x} == 0
++$$x->{x}
both look suspect. $$x->{x} is parsed as {$$x}->{x} (dereference $x, then treat it as a hash reference and look up the value with key x). I think you mean to say
${$x->{x}} == 0
++${$x->{x}}
where ${$x->{x}} means to treat $x as a hash reference, to look up the value for key x in that hash, and then to dererence that value.

In Perl, why am I getting a warning when I use #_[0], #_[1], etc to access arguments to my subroutine?

The below one the code.
sub max
{
if (#_[0] > #_[1])
{
#_[0];
}
else
{
#_[1];
}
}
print "biggest is ".&max(37,25);
When I ran it, I got the following warnings,
Scalar values #_[0] better written as $_[0] at file.pl line 3.
Scalar values #_[1] better written as $_[1] at file.pl line 3.
Scalar values #_[0] better written as $_[0] at file.pl line 5.
Scalar values #_[0] better written as $_[0] at file.pl line 9.
biggest is 37.
Although I got a correct output, but I wonder what could be the reason behind this warning, Since I think that using #_ in a subroutine would be apropriate than $_.
The problem is that you are referring to your single array element by using an array slice instead of a scalar. Just like the error says. An array slice is a list of elements from an array, for example:
my #a = (0 .. 9);
print #a[0,3,4]; # prints 034
Conversely, when you refer to a single array element you use the scalar prefix $:
print $a[3]; # prints 3
So when you do
#_[0];
Perl is telling you that the proper way to refer to a scalar value is by not using an array slice, but rather to use the scalar notation:
$_[0];
That is all.
Try to understand it with this example:
#array = (1,2,3); #array is the name of the array and # means that it's an array
print $array[1];
#this will print element at index 1 and you're doing it in scalar context
Similarly,
#_ = (1,2,3); #_ is the name of the array
print $_[1];
#this will print element at index 1 of array _ and again you're doing it in scalar context
You are referring to an array, instead of a scalar. #_[0] means ($_[0]). But perl is kind of clever so it warns You that instead of an explicit single element list You should return a scalar. Here You should use $_[0].
I suggest to use prototype, as now You could call max (1, 2, 3) and the result will be 2, instead of 3. So define as
sub max ($$) { $_[0] > $_[1]) ? $_[0] : $_[1] }
Or better, You can use for undefined number (>=2) of elements. Maybe pointless to call it with 0 or 1 items.
sub max (#) {
return undef if $#_<0;
my $s = shift;
for(#_) { $s = $_ if $_ > $s } $s
}

Why pass by ref needs shift instead of #_?

I have a question regarding pass by reference to subroutines in Perl. For values if I pass using #_ it works but for ref only shift works . Not sure why. I have givedn sample code below:
This works:
#! /usr/bin/perl
use strict;
use warnings;
my $name = 'John';
PassScalarByRef( \$name );
sub PassScalarByRef{
my $got = shift;
print "Hello $$got\n";
}
but not this one:
#! /usr/bin/perl
use strict;
use warnings;
my $name = 'John';
PassScalarByRef( \$name );
sub PassScalarByRef{
my $got = #_;
print "Hello $$got\n";
}
In the second case, assigning to $got provides a scalar context to #_, which causes it to evaluate to its size (number of elements). You can instead say:
my ($got) = #_;
...to assign the first element of #_ to $got, as you expect.
You are using the #_ array in scalar context. $got now contains the number of arguments passed. You should try my ($got) = #_, which now uses the array in list context which is what you mean.
Most operators give their operands a specific context in a consistent way; for instance, + gives both its operands scalar context; || gives its left operand scalar context and its right operand whatever context the || itself has.
Assignment is a little different, because there are two types, list assignment and scalar assignment.
Scalar assignments look like:
$scalar = ...
lvaluesub() = ...
(lvalue subs are a little-used feature of perl; the builtin pos is an example).
Only one value is being assigned, and these give ='s right operand scalar context.
List assignments look like this:
#array = ...
#arraytoslice[...] = ...
%hash = ...
#hashtoslice{...} = ...
( ... ) = ...
or even
() = ...
All these expect a list of values to assign, so give the right operand list context.
When you say:
my $got = #_;
this is a scalar assignment, and so #_ gets scalar context, which causes it to return its number of elements, not the first value.
Instead, say:
my ($got) = #_;
Some people do this consistently, even for subs with only one operand; others do
my $param1 = shift;
my $param2 = shift;
for subs with a small number of operands.
It's common for methods to get the object/class using shift and a list assignment from #_ for the remaining parameters.
Used differently.
my $got = $_[0];

Pass by reference in perl

use warnings;
use strict;
my #array = (1,2,3,4,5);
my $v = 1;
sub by_ref
{
my ($array_ref,$v) = #_;
#$array_ref = (0,0,0);
print "Array inside by_ref: #$array_ref\n";
}
by_ref(\#array,$v);
print "Array changed: #$array\n";
I'm passing #array by reference(I'm assuming I'm doing it right). I want the changes made in the sub routine on #arraybe reflected in the calling sub routine. I don't know where I have gone wrong.
Thank you in advance.
You are printing the array reference outside the subroutine too, which is wrong. The scope of array reference is limited to the subroutine only.
So you should change your last line to print only #array not #$array.
Like:
print "Array changed: #array\n";
Just change to
print "Array changed: #array\n";
and it should be ok

An array and a variable as parameters in subroutine in Perl

Consider:
sub abc()
{
}
abc(#array, $a);
How do I access #array and $a in subroutine abc()?
I know about $_[0] and $_[1], but I wasn't sure if I can use it for arrays.
You access a sub's arguments with the #_ array. The first argument is $_[0], the second - $_[1], etc. In this particular case, your array will be unrolled to list of its elements, so $_[0] is $array[0], $_[1] is $array[1] and then after all those elements, last element of #_ will be the value of $a.
If you want to avoid unrolling that always happens when you use an array in a list context, use a reference to the array instead. References to arrays and hashes are created using \. So call your function like:
abc(\#array, $a);
After that, $_[0] will have reference to #array and $_[1] will be $a. To access array elements through reference, use -> operator. $_[0]->[2] is same as $array[2]. Actually you can even drop -> as long as it is between brackets, so $_[0][2] will work too. See more details on references in perlref.
You have two options:
Pass the scalar variable first (the dirty way)
abc($a, #array);
Then receive the parameters in subroutine as
my ($a, #array) = #_;
Pass your array as reference by adding a backslash before the array variable (recommended)
abc(\#array, $a);
Then receive the parameters in subroutine as
my ($array_ref, $a) = #_;
And dereference the $array_ref
my #array = #$array_ref;
More information about perlref.
The other answers explained the two basic approaches. However, it is important to note that there is a big difference between the two: When you pass an array by reference, any changes you make to it also change the original array. Here is an example:
use warnings;
use strict;
my #array = (1, 2, 3, 4, 5);
sub by_ref
{
my $array_ref = $_[0];
#$array_ref = (0, 0, 0);
print "Array inside by_ref: #$array_ref\n";
}
sub by_val
{
my #array_copy = #_;
#array_copy = (0,0,0);
print "Array inside by_val: #array_copy\n";
}
by_val(#array);
print "Original array after calling by_val: #array\n";
by_ref(\#array);
print "Original array after calling by_ref: #array\n";
If you do pass by reference, you need to keep this behavior in mind, making a copy of the referenced array if you don't want changes made in your sub to affect the original.
It would be nice if you pass the array reference instead of an array as mentioned by Oleg V. Volkov like
sub abc()
{
my ( $array, $a ) = #_; #receiving the paramters
my #arr = #{$array}; # dereferencing the array
}
abc(\#array,$a);