Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
Why my sub cannot get hidden in the scope of function such in
use strict;
sub out{
my sub this{my $n=9;print "\n$n"} my $i=7; my $j=3
}
&this;
9
Please help solve
As described in the documentation in perldoc perlsub, a lexical subroutine is only visible inside the block they are created:
These subroutines are only visible within the block in which they are declared...
You try to call the sub outside the block, therefore Perl cannot see it. This is also the entire point of using lexical scope: You are trying to restrict the range.
If you had use warnings enabled you would get the warning:
Undefined subroutine &main::this called at ...
You have to use the lexical sub inside the block -- in this case another sub -- like this:
sub out {
my sub this {
....
}
this(); # <---- visible here
}
this(); # wrong, not visible here
Also, using & when calling a sub has a special meaning. As described in perlsub:
&NAME; # Makes current #_ visible to called subroutine.
The normal way to call a sub is by adding parens after: this(). The different ways to call a sub are also listed in perldoc perlsub. Note that there is hidden functionality in the different styles.
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
&NAME; # Makes current #_ visible to called subroutine.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've created a subroutine named "MENU" with a label named "INIT_MENU" at the top of the subroutine, but when i call this label i got a error : Can't goto subroutine outside a subroutine at program.pl line 15
Here is an example:
sub MENU {INIT_MENU: print "blah blah";}
and here is the line 15:
goto &MENU, INIT_MENU;
Sorry if it is a duplicated question, i searched in all possible places and even in the official site of Perl
The goto expects a single argument, so this code first executes goto &MENU and then after the comma operator it evaluates the constant INIT_MENU in a void context (drawing a warning).
The purpose of goto &NAME is to replace the subroutine in which it is encountered with subroutine NAME; it doesn't make sense calling it outside of a subroutine and this is an error. From perldiag
Can't goto subroutine outside a subroutine
(F) The deeply magical "goto subroutine" call can only replace one subroutine call for another. It can't manufacture one out of whole cloth. In general you should be calling it out of only an AUTOLOAD routine anyway. See goto.
A comment on the purpose of this.
A lot has been written on the harmfulness of goto LABEL.† Not to mention that INIT_MENU: cannot be found when hidden inside a routine. The upshot is that there are always better ways.
A sampler
Call the function and pass the parameter
MENU(INIT_MENU);
sub MENU {
my $menu = shift;
if ($menu eq 'INIT_MENU') { ... }
...
}
If, for some reason, you want to 'hide' the call to MENU use goto &MENU as intended
sub top_level { # pass INIT_MENU to this sub
...
goto &MENU; # also passes its #_ as it is at this point
# the control doesn't return here; MENU took place of this sub
}
This altogether replaces top_level() with MENU() and passes on its #_ to it. Then process input in MENU as above (for example) to trigger the chosen block. After this "not even caller will be able to tell that this routine was called first," see goto. Normally unneeded
Why even have MENU()? Instead, have menu options in separate subs and their references can be values in a hash where keys are names of options. So you'd have a dispatch table and after the logic (or user choice) selects a menu item its code is run directly
my %do_menu_item = ( INIT_MENU => sub { code for INIT_MENU }, ... );
...
$do_menu_item{$item_name}->();
Menu systems tend to grow bigger and more complex with development. It would make sense to adopt OO from start, and then there are yet other approaches for this detail
If you find yourself considering goto it may be time to reconsider (some of) the design.
† See for instance this post and this post. It's (even) worse than that in Perl since there are specific constructs (and restrictions) for situations where goto can be argued acceptable, so there is even less room for it. One example is jumping out of nested loops: there are labels in Perl.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i have assigned a global variable at start of my script which is empty string and i assigned a value to that inside subroutine . When the script enters the subroutine second time that variable is null and assigned new value .
I need to have the variable name constant for some subroutine calls and then change the value in the subroutine when my condition match
first time it call the subroutine this variable will be empty enter the loop and in the loop i will assign the variable.. next time when it enter the sub routine i want to use that variable value until the condition is met .
Here is the sample code
#!/usr/bin/perl
my $Next_5minus = '';
sub write_alog {
if (my $Next_5minus eq '')
{
........
.........
}
elsif ( $start_mtime < $end_mtime )
{
say $fh join("\n", #$alog);
}
elsif ( $start_mtime > $end_mtime )
{
my $Next_5minus = <will assign value>
..........
}
}
If you want people to help you with your problems, it's polite to make it as simple as possible for them to help you. As a minimum, you should do the following:
Provide a short, self-contained, runnable program that demonstrates your problem.
Clean up the indentation in your code to make it easy to follow.
Add use strict and use warnings to your code and clean up the problems they point out.
In this case, I suspect you'll see warnings about variables that mask variables of the same name. You define three copies of your $Next_5minus variable. Each of them will be initialised as undef as it is created and will disappear as it goes out of scope.
Try removing the extraneous my statements from your code and see if that fixes your problem.
This question already has answers here:
What does the function declaration "sub function($$)" mean?
(2 answers)
Closed 7 years ago.
What dose the ( $$ ) do in this code. I have programmed Perl for a long time but never came across this syntax until recently when I opened a very old Perl .plx file
These rows prevent me from upgrading to a more modern Perl version.
sub help( $$ ){
}
The reason it affects me is because I get an error message stating that the help function was called before it was declared. Any idea of how I can solve this without removing the ( $$ ) block??
The are called prototypes. This particular one says that the sub routine expects to be called with exactly 2 scalar variables. Although prototypes are sometimes useful, mostly they are not.
If you can drop them depends on the rest of the code...
That's a function prototype, which is used to specify the number and types of arguments that the subroutine takes. See the documentation.
Since it's in the current documentation, I don't see why it's preventing you from upgrading.
Is the error you're getting help called too early to check prototype? Here's the explanation from the perldiag documentation:
(W prototype) You've called a function that has a prototype before the parser saw a definition or declaration for it, and Perl could not check that the call conforms to the prototype. You need to either add an early prototype declaration for the subroutine in question, or move the subroutine definition ahead of the call to get proper prototype checking. Alternatively, if you are certain that you're calling the function correctly, you may put an ampersand before the name to avoid the warning. See perlsub.
It's a prototype. The $$ specifies that the help function expects two arguments and that they should each be evaluated in scalar context. Note that this does not mean that they are scalar values! Perl's prototypes aren't like prototypes in other languages. They allow you to define functions that behave like built-in functions: parentheses are optional and context is imposed on the arguments.
sub f($$) { print "#_\n" }
my #a = ('a' .. 'c');
f(#a, 'd'); # prints "3 d"
I'm guessing that the error message you're seeing is
help() called too early to check prototype
which means that Perl saw a call to the function before it saw the declaration of the function and knew about the prototype. This means that the prototype wasn't enforced and the call may not behave as expected.
my #a = ('a' .. 'c');
f(#a, 'd'); # prints "a b c d"
sub f($$) { print "#_\n" }
To fix the error you need to either move the subroutine definition before the call, or add a declaration before the call.
sub f($$); # forward declaration
my #a = ('a' .. 'c');
f(#a, 'd'); # prints "3 d"
sub f($$) { print "#_\n" }
All of this should have absolutely nothing to do with your ability to upgrade to a newer version of Perl.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Inspired by the original thread and the up and coming clones, here's one for the Perl community.
What are questions a good Perl programmer should be able to respond to?
Why is use strict helpful?
My bellweather question is What's the difference between a list and an array?.
I also tend to like asking people to show me as many ways as they can to define a scope. There's one that people almost always forget, and another that most people think provides a scope but doesn't.
What is the difference between
if ($foo) { ... }
and
if (defined $foo) { ... }
and when should you use one over the other?
Questions
What is a reference?
How does Perl implement object orientation?
How does Perl's object orientation differ from other languages like C# and Java?
Traditional object orientation in core Perl has largely been superseded by what?
Why?
What is the difference between a package and a module?
What features were implemented in 5.10?
What is a Schwartzian transform?
Explain the difference between these lines of code and the values of the variables.
my $a = (4, 5, 6);
my #a = (4, 5, 6);
my $b = 4, 5, 6;
my $c = #a;
What are some of Perl's greatest strengths?
What are some of Perl's greatest weaknesses?
Name several hallmarks of the "modern Perl" movement.
What does the binding operator do?
What does the flip-flop operator do?
What is the difference between for and foreach?
What makes Perl difficult to parse?
What are prototypes?
What is AUTOLOAD?
What is the Perl motto?
Why is this a problem?
What does use strict; do? Why is it useful?
What does the following block of code do?
print (3 + 4) * 2;
Tests
Implement grep using map.
Implement and use a dispatch table.
Given a block of text, replace a word in that block with the return value of a function that takes that word as an argument.
Implement a module, including documentation compatible with perldoc.
Slurp a file.
Draw a table that illustrates Perl's concept of truthiness.
What is the difference between my and our?
What is the difference between my and local?
For the above, when is it appropriate to use one over the other?
What are list context and scalar context?
What is the difference between my $x = ... and my($x) = ...?
What does my($x,undef,$z) = ... do?
Why is my(#a,#b) = (#list1, #list2) likely a bug?
How can a user-defined sub know whether it was called in list or scalar context? Give an example of when it makes sense for the same sub to return different values in one context or the other.
What is the difference between /a(.*)b/ and /a(.*?)b/?
What's wrong with this code?
my #array = qw/a b c d e f g h/;
for ( #array ) {
my $val = shift #array;
print $val, "\n";
}
my $a = 1;
if($a) {
my $a = 2;
}
print $a;
What is the value of $a at the end?
What's wrong with using a variable as a variable name?
Study guide: Part 1, Part 2, and Part 3.
I think brian d foy's approach is an ingenious tactic to test knowledge, understanding, and partiality about the language and the programming craft in general: What are five things you hate about your favorite language?. If they can't name 5 they probably aren't great with the language, or are totally inept at other approaches.
He applies this to people trying to a push a language: I would extend that and say it is just as applicable here. I would expect every good Perl programmer to be able to name five things they don't like. And, I would expect those five things to have some degree of merit.
Write code that builds a moderately complex data structure, say an array of hashes of arrays. How would you access a particular leaf? How would you traverse the entire structure?
For each of the following problems, how would you solve it using hashes?
Compute set relationships, e.g., union, intersection, mutual exclusion.
Find unique elements of a list.
Write a dispatch table.
My favourite question. What is following code missing:
open(my $fh, "<", "file.txt");
while (<$fh>) {
print $_;
}
close($fh);
This question should open discussion about error handling in perl. It also can be adopted to other languages too.
Some months ago, chromatic—author of Modern Perl—wrote a similar nice article “How to Identify a Good Perl Programmer,” which contains a list of questions that every good Perl programmer should be able to answer effectively.
Some of those nice questions are given below:
What’s the difference between accessing an array element with $items[$index] and #items[$index]?
What’s the difference between == and eq?
How do you load and import symbols from a Perl 5 module?
What is the difference, on the caller side, between return; and return undef;?
What is the difference between reading a file with for and with while?
For complete details read How to Identify a Good Perl Programmer.
How is $foo->{bar}[$baz]($quux) evaluated?
What is a lexical closure? When are closures useful? (Please, no counter-creators!)
What is the difference between list context and scalar context. How do you access each? Is there such a thing as Hash context? Maybe a little bit?
How to swap the values of two variables without using a temporary variable?
What does this one-liner print and why :
perl -pe '}{$_ = $.' file
answer: number of lines in the file, similar to wc -l.
What's wrong with this code :
my $i;
print ++$i + ++$i;
answer: modifying a variable twice in the same statement leads to undefined behaviour.
Simple one: will the if block run :
my #arr = undef;
if (#arr) { ... }
answer: yes
How would you code a reverse() perl builtin yourself ? You can use other perl functions.
answer: many ways. A short one: sub my_reverse {sort {1} #_})
I would also probably dig on regex, as I expect every good Perl programmer to master regex (but not just that). Some possible questions:
what are lookahead and lookbehind assertion /modifierq?
how do you check that two individual parts of a regex are identical ?
what means greedy ?
what are Posix character classes ?
what does \b match ?
what is the use of \c modifier ?
how do you precompile a regex ?
What is the correct way to initialize a empty string?
my $str = q{};
or
my $str = "";
or
my $str = '';