Script dies if a module that doesnt exist is used during sort() - DateTime::TimeZone::Local example - perl

use DateTime::TimeZone::Local;
use Test::More tests => 1;
my #input = (1 .. 10 );
my (#output) = sort {
DateTime::TimeZone::Local->TimeZone();
$a cmp $b
} #input;
is_deeply(\#output, \#input);
Output:
1..1
Can't return outside a subroutine at /usr/local/share/perl/5.8.8/DateTime/TimeZone/Local.pm line 72.
# Looks like your test exited with 9 before it could output anything.
shell returned 9
I have checked and it definitely is inside a sub routine. It doesn't appear to be anything to do with the module used, this code also causes the same error:
my #output = sort {
sub1();
} (1 .. 5);
sub sub1 {
eval "use ModuleDoesntExist";
return 1; # remove this and get a seg fault
}
Looks like it is a bug in perl more than anything. Any ideas? More interested in why this is happening than a workaround - it only occurs if the module doesn't exist.

It looks as though it is actually a bug in Perl. See this thread on the Perl Porters list.

Related

Return from sort block gives "Use of uninitialized value in sort" warning, but only with explicit return

I'm getting a strange behavior from Perl when I try to return from my sort() block:
#!/usr/bin/perl
use strict;
use warnings;
my #data = sort {
return &special_sort;
} qw/ 6 1 2 /;
use Data::Dumper;
print STDERR Data::Dumper->Dump([\#data]);
sub special_sort {
# (imagine some custom sorting logic here)
return $a <=> $b;
}
This gives the following messages:
Use of uninitialized value in sort at ./mcve.pl line 6.
Use of uninitialized value in sort at ./mcve.pl line 6.
Use of uninitialized value in sort at ./mcve.pl line 6.
$VAR1 = [
6,
1,
2
];
As you can see, it also failed to sort the list. The odd thing is, the following sort clauses work without any warnings, and sort the data properly:
my #data = sort {
&special_sort;
} qw/ 6 1 2 /;
my #data = sort {
my $res = &special_sort;
return $res;
} qw/ 6 1 2 /;
my #data = sort {
return $a <=> $b;
} qw/ 6 1 2 /;
my #data = sort {
eval { return &special_sort; }
} qw/ 6 1 2 /;
Question 0
What's going on here? Why do those four work, but the first example doesn't? It shouldn't be the return statement causing undefined behavior, since two of the working ones have that.
Question 1
If it turns out the world isn't perfect and I can't (or shouldn't) return from a block, is there an elegant way to effectively do that?
Edit: It was a bug in Perl. (Note: I did some checking, and I'm slowly figuring out this is down to my confusion between how Perl handles BLOCKs vs. SUBs, hence Question 1. The question is still interesting IMO, and confusing behavior on Perl's part.)
For clarity, I'm using Perl 5.32.0.
This is a bug. A fix has been applied, resolving the issue in upcoming Perl 5.34.
In the meantime, you can replace
return &special_sort;
with
&special_sort; # Avoids the issue.
or
return scalar( &special_sort ); # Force scalar context.
or
return 0+&special_sort; # Force scalar context.
The problem is that special_sort is incorrectly being called in void context, which is avoided or circumvented by the above workarounds.
I initially claimed that you can't use return in a sort block because it's not a sub. I also indicated I was confused by the fact that no error was reported. #Håkon Hægland points out that the documentation for return indicates it can be used in sort block. And indeed it can be used in other circumstances. There's a bug, which I've reported and which has now been fixed.

How to fix "Experimental values on scalar is now forbidden"

In Perl 5.26.1 I get:
Experimental values on scalar is now forbidden at /funcx.pm line 110.
Where line 110 is the foreach in
sub checkSsh {
foreach my $slave (values $::c{slaves}) {
...
}
}
$c contains
$VAR1 = {
'slaves' => {
'48' => '10.10.10.48'
},
};
where
our %c = %{YAML::Syck::LoadFile($config)};
Question
What is actually the problem? And how should it be fixed?
Perl is complaining that you are calling the values builtin on a SCALAR, in this case a HASHREF:
Properly de-referencing your slaves key allows values to work as expected:
foreach my $slave ( values %{ $c{slaves} } ) {
...
}
As to the specific warning you receive, they address that directly in the perldoc page:
Starting with Perl 5.14, an experimental feature allowed values to
take a scalar expression. This experiment has been deemed
unsuccessful, and was removed as of Perl 5.24.
To avoid confusing would-be users of your code who are running earlier
versions of Perl with mysterious syntax errors, put this sort of thing
at the top of your file to signal that your code will work only on
Perls of a recent vintage:
use 5.012; # so keys/values/each work on arrays

How to convince Devel::Trace to print the BEGIN-block statements?

Have a simple script p.pl:
use strict;
use warnings;
our $x;
BEGIN {
$x = 42;
}
print "$x\n";
When I run it as:
perl -d:Trace p.pl
prints:
>> p.pl:3: our $x;
>> p.pl:7: print "$x\n";
42
how to get printed the BEGIN block statements too, e.g. the $x = 42;?
Because my intention isn't clear, adding the clarification:
Looking for ANY way to print statements when the perl script runs (like Devel::Trace it does) but including the statements in the BEGIN block.
It's very possible. Set $DB::single in an early BEGIN block.
use strict;
use warnings;
our $x;
BEGIN { $DB::single = 1 }
BEGIN {
$x = 42;
}
print "$x\n";
$DB::single is a debugger variable used to determine whether the DB::DB function will be invoked at each line. In compilation phase it is usually false but you can set it in compilation phase in a BEGIN block.
This trick is also helpful to set a breakpoint inside a BEGIN block when you want to debug compile-time code in the standard debugger.
Disclaimer: This is just an attempt to explain the behaviour.
Devel::Trace hooks up to the Perl debugging API through the DB model. That is just code. It installs a sub DB::DB.
The big question is, when is that executed. According to perlmod, there are five block types that are executed at specific points during execution. One of them is BEGIN, which is the first.
Consider this program.
use strict;
use warnings;
our ($x, $y);
BEGIN { $x = '42' }
UNITCHECK { 'unitcheck' }
CHECK { 'check' }
INIT { 'init' }
END { 'end' }
print "$x\n";
This will output the following:
>> trace.pl:8: INIT { 'init' }
>> trace.pl:3: our ($x, $y);
>> trace.pl:11: print "$x\n";
42
>> trace.pl:9: END { 'end' }
So Devel::Trace sees the INIT block and the END block. But why the INIT block?
Above mentioned perlmod says:
INIT blocks are run just before the Perl runtime begins execution, in "first in, first out" (FIFO) order.
Apparently at that phase, the DB::DB has already been installed. I could not find any documentation that says when a sub definition is run exactly. However, it seems it's after BEGIN and before INIT. Hence, it does not see whatever goes on in the BEGIN.
Adding a BEGIN { $Devel::Trace::TRACE = 1 } to the beginning of the file also does not help.
I rummaged around in documentation for perldebug and the likes, but could not find an explanation of this behaviour. My guess is that the debugger interface doesn't know about BEGIN at all. They are executed very early after all (consider e.g. perl -c -E 'BEGIN{ say "foo" } say "bar"' will print foo.)

Simple Perl Script: Two questions

I have a small program:
#!/user/bin/perl
use strict;
system ("clear");
my($option, $path);
do
{
print "\tEnter the number of your chosen option:\n";
print "\n";
print "\tOption\t\tCommand\n";
print "\t======\t\t=======\n";
print "\t1\t\tDate\n";
print "\t2\t\tDirectory Listing\n";
print "\t3\t\tCalendar\n";
print "\t4\t\tVi Editor\n";
print "\t5\t\tCalculator\n";
print "\t6\t\tExit\n\n";
chomp($option=<STDIN>);
SWITCH:
{
($option =="1") and do
{
system(date);
last;
};
($option =="2") and do
{
print "Enter the path:"; ############################
chomp($path=<STDIN>); #This is giving me an error#
system(ls $path); ############################
last;
};
($option =="3") and do
{
system(cal);
last;
};
($option =="4") and do
{
system(vi);
last;
};
($option =="5") and do
{
system(bc);
last;
};
}
}while ($option!=6);
print "Goodbye!\n";
sleep 2;
First question: Can anyone help me how to write the proper command to create a directory listing in case 2.
Second Question: Why do I get a loop if I use
$date = `date`;
print "$date";
instead of
system(date);
You should be able to solve a lot of your problems by remembering to put quotes around literal arguments to system():
system("date");
system("ls $path");
and the same for most other places you call system() (your first call to system("clear") is correct).
It is a quirk of Perl that calling something like system(cal) works at all, because the unquoted cal is treated as a "bareword" by Perl, which happens to be roughly equivalent to a string when passed to a function such as system(). Relying on this behaviour would be terribly bad practice, and so you should always quote literal strings.
You could read the path like:
chomp($path=<STDIN>);
system("ls $path");
Not sure why you'd get the loop for $date =date;print "$date";. But I don't think there's a date function unless you're using a package for it. You can show a time like:
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
$year += 1900;
$mon += 1;
printf "%04d-%02d-%02d %02d:%02d:%02d",
$year, $mday, $mon,
$hour, $min, $sec;
On most unix systems perl resides in /usr/bin, without the e in user, so you might consider double-checking the first line of your script.
Your immediate problems were caused by quoting issues and the lack of use warnings in your script.
It's also worth noting that menu-driven scripts like yours are ideal candidates for dispatch tables. A dispatch table is a technique for defining actions as data. The actions are Perl subroutines. The data is usually a set of key-value pairs that end up getting stored in a hash.
The keys to the hash are the choices made by the user (menu items 1-6 in your case).
The values in the hash are called code references. There are two ways to set up these code references: (1) Directly in the dispatch table, using anonymous subroutines; or (2) using the &\foo syntax, which would create a reference to a subroutine named foo.
The handy thing about this approach is that your menu() method can be reused -- simply with a different dispatch table and a different usage message.
This example is so small that the benefit of reuse might not seem compelling, but the general technique of having data -- in the form of a dispatch table -- control program behavior is powerful in many contexts.
# Always use both of these.
use strict;
use warnings;
sub dispatch_table {
return
1 => sub { system 'date' },
2 => \&ls_path,
3 => sub { system 'cal' },
4 => sub { system 'vi' },
5 => sub { system 'bc' },
6 => sub { print "Goodbye!\n"; sleep 2 },
;
}
sub ls_path {
print "\nEnter the path: ";
chomp(my $path=<STDIN>);
# Note quoting. To be super robust, you would
# need to escape apostrophes in the path.
system "ls '$path'";
}
sub usage_message {
return "Choose wisely:
Option Command
====== =======
1 Date
2 Directory Listing
3 Calendar
4 Vi Editor
5 Calculator
6 Exit
";
}
sub menu {
system 'clear';
my %dt = dispatch_table();
my $option;
print usage_message();
while (1){
print "> ";
chomp($option = <STDIN>);
last if exists $dt{$option};
}
$dt{$option}->();
}
menu();
I can not reproduce your loop with:
$date =date;print "$date";
I doubt that is exactly how you coded it since I get a compile error
with use strict;. If you can show a reduced code example which still illustrates the problem, we could help debug it further.
If you are trying to capture the output of an external command into a variable, you could use backticks or qx:
my $date = qx(date);
print "$date";
On a side note, whenever I see a series of print statements, I think here-doc:
print <<"EOF";
Enter the number of your chosen option:
Option Command
====== =======
1 Date
2 Directory Listing
etc...
EOF
A little easier to read and maintain, no?
Finally, it is also a good idea to use warnings;.
The first couple of suggests I have are, first like others have already suggested, use warnings is strongly encouraged. Older Perl interpreters may require you use the older form #!/usr/bin/perl -w as the first line of your Perl script. Second, there is a Switch module available, to make the switch statement look less ugly. I've also shown usage of subroutines to clean up the appearance of the program.
I've attached a alternative version of your script with some potential suggestions. Note it uses a slightly different alternative for switch. If available, I'd recommend using the Switch module. It includes a different way of printing the time, and of course fixes your problem with the system calls.
I hope that helps.
#!/usr/bin/perl
use strict;
use warnings; # otherwise /usr/bin/perl -w in first line
sub menu() {
print <<EOM;
Enter the number of your chosen option:
Option Command
====== =======
1 Date
2 Directory Listing
3 Calendar
4 Vi Editor
5 Calculator
6 Exit
EOM
}
sub showtime() {
my $time = localtime;
print $time,"\n";
}
sub listdir() {
my $path;
print "Enter the path: ";
chomp($path = <STDIN>);
system("ls $path");
print "\n";
}
system("clear");
my $option;
do {
menu();
chomp($option = <STDIN>);
# SWITCH:
for ($option) {
/1/ and do {
showtime();
};
/2/ and do {
listdir();
};
/3/ and do {
system("cal");
};
/4/ and do {
system("vi");
};
/5/ and do {
system("bc");
};
last;
}
} while ($option != 6);
print "Goodbye!\n";
sleep 2;

How do I rerun a subroutine without restarting the script in Perl's debugger?

Suppose I have a situation where I'm trying to experiment with some Perl code.
perl -d foo.pl
Foo.pl chugs it's merry way around (it's a big script), and I decide I want to rerun a particular subroutine and single step through it, but without restarting the process. How would I do that?
The debugger command b method sets a breakpoint at the beginning of your subroutine.
DB<1> b foo
DB<2> &foo(12)
main::foo(foo.pl:2): my ($x) = #_;
DB<<3>> s
main::foo(foo.pl:3): $x += 3;
DB<<3>> s
main::foo(foo.pl:4): print "x = $x\n";
DB<<3>> _
Sometimes you may have to qualify the subroutine names with a package name.
DB<1> use MyModule
DB<2> b MyModule::MySubroutine
just do: func_name(args)
e.g.
sub foo {
my $arg = shift;
print "hello $arg\n";
}
In perl -d:
DB<1> foo('tom')
hello tom
Responding to the edit regarding wanting to re-step through a subroutine.
This is not entirely the most elegant way of doing this, but I don't have another method off the top of my head and am interested in other people's answers to this question :
my $stop_foo = 0;
while(not $stop_foo) {
foo();
}
sub foo {
my $a = 1 + 1;
}
The debugger will continually execute foo, but you can stop the next loop by executing '$stop_foo++' in the debugger.
Again, I don't really feel like that's the best way but it does get the job done with only minor additions to the debugged code.