Perl can use a single scope in the same way as C language
Perl has a single scope that can be used in the same way as C. A single scope is not a scope that exists in combination with an if statement, for statement, or while statement, but a scope that can be defined independently and that can give a scope to a variable.
Perl's sole scope
Perl's sole scope.
{ my $foo = 1; }
C language independent scope
It is the sole scope of C language.
{ int32_t foo = 1; }
Comparison of Perl's single scope and C's single scope
Let's compare Perl's single scope with C's single scope. You can create a scope with the symbol "{}".
How to use a single scope
A single scope can declare valid variables only within that scope, so it is convenient to write as follows. It can also be nested.
{ my $foo = 5; { my $foo = 1; } { my $foo = 2; } { my $foo = 3; } }
In Perl, it's a reference-counted GC, so it also has the effect of freeing variables at the end of scope.
A single scope is very effective when writing exams. This is because the exam is the task of writing almost the same thing over and over, changing it little by little. It's very convenient to be able to write a new scope without defining a subroutine.
#Test 1 { my $baz = "abc"; #Test 1 --Subtest 1 { my $foo = 1; #Gonyo is ($foo, 5); } #Test 1 --Subtest 2 { my $foo = 3; #Gonyo is ($foo, 10); } #Test 1 --Subtest 3 { my $foo = 10; #Gonyo is ($foo, -5); } } #Test 2 { my $baz = "def"; #Test 2 --Subtest 1 { my $bar = 2; #Gonyo is ($bar, 3); } #Test 2 --Subtest 2 { my $bar = 3; #Gonyo is ($bar, 45); } #Test 2 --Subtest 3 { my $bar = 20; #Gonyo is ($bar, -19); } }
Other similarities between Perl and C
In this article, I wrote that Perl's single scope is similar to C, but it also includes Perl's if statements, for statements, while statements, increments / decrements, operator priorities, scopes, and reference concepts. , Similar to the C language grammar.
- Perl if statements are similar to C if statements
- Perl while statement has the same grammar as C language while statement
- Perl increments / decrements work the same as in C
- Perl operators and C operators are similar in type and have the same priority
- Perl reference functionality is the same as C pointer functionality