Is local a bad part in Perl?

is-local-a-bad-part-in-perl?

Q. Is local a bad part in Perl?

A. In my opinion, Yes. local is a bad part in Perl. If I could re-implement Perl, I will not implement local.

local $foo;

Q. Why does local a bad part?

A. This is because the variable that is the operand of local is a global variable although at a glance it looks like a local variable in C.

int32_t foo;

Q. What should be used instead of local?

Using my in all Perl programs is recommended strongly.

my $foo;

This is called a lexical variable. This is strange name we don’t usually hear in daily life.

Q. Does local need to be used in current days.

Q. I want to say No, but in some cases, local is used in current days. One is to save and restore predefined global variable.

{
  # Save
  local @ARGV;
}

# Restore @ARGV at the end of the scope

Tow is to get the whole content of a file.

my $content = do { local $/; <$fh>; };

Ugly, user experience is worse than other programing languages, but most efficient way because Perl doesn’t have the function to get the whole content of a file.

The efficient is sacrificed, the following code can be written.

my $content = join('', <$fh>);

Q. Are there ways to restore lexical variables?

Yes, using Scope::Guard.

Total
5
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
improve-product-discoverability-with-new-walmart-item-spec-v4.x

Improve Product Discoverability with New Walmart Item Spec v4.X

Next Post
building-recursive-logic-with-step-functions

Building recursive logic with Step Functions

Related Posts