Softpanorama

Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)
Skepticism and critical thinking is not panacea, but can help to understand the world better

Perl as powerful and flexible tool for Unix system administrators and defensive programming in Perl

Perl was developed as the language for processing logs for NSA,
then emerged as the language of choice for elite Unix sysadmins,
then enjoyed a short love affair with CGI programming but quickly was displaced by PHP
(PHP started out as a set of "Perl hacks" and cloned many Perl features),
and now returned to its roots -- it again became the language for elite Unix sysadmins

News

Scripting Languages

eBook: Perl for system admins

Recommended Perl Books Recommended Links Defensive programming Perl Language Perl Reference
Perl as a command line tool Perl Regular Expressions Overview of Perl regular expressions More Complex Perl Regular Expressions Perl namespaces Perl modules Subroutines and Functions Pipes
Perl Debugging Perl applications Perl One Liners HTML Matching Examples Perl IDE Perl Certification Notes on Perl Hype Perl for Win32
Perl Style Beautifiers and Pretty Printers Neatperl -- a simple Perl prettyprinter  Perl Xref Perl power tools Perl IDE and Programming Environment Perl Warts Perl Error Checklist
Larry Wall Larry Wall Articles and Interviews Perl evolution  Perl history Perl-related Humor Larry Wall On Perl, Sep 06 2002 Larry Wall Computerworld Interview, 2008 Larry Wall interview to Linux Format, Aug 14, 2009
Perl POD documentation Annotated Perl Articles Quotes Larry Wall - Wikiquote Tips Sysadmin Horror Stories Humor  

Introduction

 
  • Anything that can go wrong will go wrong.
  • Nothing in programming is as easy as it looks. Everything takes at least twice longer than you think.
  • If there is a possibility of several things going wrong, the one that will cause the most damage will be the one to go wrong.
    • Corollary: If there is a worse time for something to go wrong, it will happen then.
  • If anything simply cannot go wrong, it will anyway. If you perceive that there are four possible ways in which a procedure can receive wrong  parameters, there is always be a fifth way.
  • Due to maintenance and enhancements which breaks conceptual integrity programs tend to degenerate from bad to worse and number of bugs in later version does not decrease. It increases.
  • If logs suggest everything seems to be going well, you have obviously overlooked something.
  • Hardware always sides with the flaws in software.
  • It is extremely difficult to make a program foolproof because fools are so ingenious.
  • Whenever you set out to do something really important, something else comes out that should be done first.
  • Every solution of a problem breeds new problems, often more nasty...

Murphy laws of engineering
(author adaptation)

Defensive programming is a style of programming which stems from programming style adopted by compiler writers who represent the elite of the programming community and includes such names as:

and many other. We can add several people who developed scripting language interpreters:

You can only design and write a few compilers from a reasonably complex language in your lifetime (Nicklaus Wirth manages to write three, and while the languages involved were not on the level of complexity of PL/1 or Perl, this probably is a record).  Besides the complexity of the code generation, hardware moves head for those years you are writing it, making some compromises during the design phase obsolete. So creating a solid architecture of a portable complier for a particular language correctly guessing trends in hardware for the next several years and writing a successful is a high art of system programming. The art which can be mastered  by a few especially gifted programmers.  

The basic idea behind this approach is to write the program like a compiler so that it is able to run properly even through unforeseen input by users. In many ways, the concept of defensive programming is much like that of defensive driving, in that it tried to anticipate problems before they arise. One common feature is the ability handle strange input without crashing or creating a disaster.

In a way, defensive programming tried to eliminate many bugs before they happen. The classic example of "non-defensive" programming is the absence of checking of a return code for an external routine or some Unix utility. This type of bugs often slips in production code and they are discovered only during production runs, possibly many years from initial release of the product, often at a great cost. Just enforcement of the rule that no external module or utility can be used without checking its return code prevent many bugs from happening. 

In general the deeper in development cycle you find the bug, the more costly it is for fix. So while defensive programming might produce some minor overhead in both source code lines count and the run time (which for system utilities does not matter at all)  it dramatically cheapens the total development costs as fewer bugs slip into most costly for detention and elimination stage: the production phase. 

That essentially means that that the program is written in such way that it is able to able to protect itself against all invalid inputs. Which is the standard behaviour of the complier, but which can be extended to other types of programs.  It also emphasizes the quality of diagnostic of wrong inputs and situations and "intelligent" dealing with those that still can guarantee the correct results.

The invalid inputs (aka bad data) can come from user input via the command line, as a result undetected errors on other parts of the program, as a special conditions related to various objects such as file (i/o error in the file, missing file, insufficient permissions, etc). Bad data can also come from other routines in your program via input parameters. Defensive programming is greatly facilitated by an awareness of specific, typical blunders (aka SNAFU),  and vulnerabilities ( for example for sysadmin scripts and utilities a collection of "Horror Stories"  exists; see for example Creative uses of rm )

In other words, defensive programming is about making the software work in a predictable manner in spite of unexpected inputs.

Another "re-incarnation" of this concept can be traced to the period of creation of ADA programming language (1977-1983) or even earlier in the context of writing real time software.   Former DOD standard for large scale safety critical software development emphasized encapsulation, data hiding, strong typing of data, minimization of dependencies between parts to minimize impact of fixes and changes. Which is the right dose (determining of which requires programming talent) can improve the quality of programs and simplify ( but not necessary shorten ) the debugging and testing stages of program development.

One typical problem in large software modification is that creating changes by person who is not the original developer often damages conceptual integrity of the product. In this case fixing one problem creates multiple others still to be detected and fixed (one step forward, two steps back).  One way to fight this problem of "increasing entropy with age" or loss of conceptual integrity is to institute a set of  sanity checks which detect abnormal parameters values (assertions or some similar mechanism). In most systems resulting overhead is negligible as such check usually are administered outside the most inner loops. but the positive effect is great. 

Many people independently came to the subset of ideas of defensive programming, so it is impossible to attribute this concept to a single author. As an example of early attempt to formulate some principles of defensive programming style we can list  Tom Christiansen recommendations (Jan 1, 1998) for Perl language. Perl does not have strict typing of variables and, by default, does not  require any declaration of variables, creating potential for misspelled variables slipping into production version of the program. (unless you use strict pragma -- the use the latter became standard in modern Perl). While they are more then 20 years old they are still relevant:  

Out of those the most interesting is taint option (strict is also interesting but it simply partially fixes oversights in the initial design of the language; Python uses more sound idea of typing values and requires explicit conversion between values of different types). Here is a quote from Perl Command-Line Options - Perl.com:

The final safety net is the -T option. This option puts Perl into "taint mode." In this mode, Perl inherently distrusts any data that it receives from outside the program's source -- for example, data passed in on the command line, read from a file, or taken from CGI parameters.

Tainted data cannot be used in an expression that interacts with the outside world -- for example, you can't use it in a call to system or as the name of a file to open. The full list of restrictions is given in the perlsec manual page.

In order to use this data in any of these potentially dangerous operations you need to untaint it. You do this by checking it against a regular expression. A detailed discussion of taint mode would fill an article all by itself so I won't go into any more details here, but using taint mode is a very good habit to get into -- particularly if you are writing programs (like CGI programs) that take unknown input from users.

Is Perl dying ? No, it remains an essential and very popular tool for system administrators,
probably the best second language after BASH unless you learned Python at the college

There are a lot well-meaning and not so well meaning  pundits who claim that Perl is dying, etc. But after language became widespread and complier/interpreter is still supported and is included into all major OSes, it can only fade but never die. Just look at the Fortran.

As for Python popularity it is connected with the power of modern computers. On computers typical for say 1996 Python did not stand a chance. Yo asset the level of overhead Python impose on programmer  watch Advanced Python or Understanding Python - YouTube. This is pretty realistic assessment  of the complexity of the Python (and by extension inefficiency of its implementation). All this public masturbation with multiple inheritance and other esoteric concepts are so far from problems sysadmin need to solve that you probably should stay clear of this language put of principle, unless Perl get into real trouble. You better try to learn Golang instead, as, at least, it is faster then Python ten times or more :-).  Go deliberately omits certain OO features that does not have much value but increase overhead, including inheritance and generic programming: two favorite topics of language complexity junkies.

Perl has an interesting historical path: from a language for elite system administrators to mass Web development  language and back to the tool for elite system administrators.  Several (or may be most) early adopters of Perl such as  Randal L. Schwartz  and Tom Christiansen (author of Csh Programming Considered Harmful, 1995  ) were outstanding Unix  system administrators.

Perl has an interesting historical path: from a language for elite system administrators to mass Web development language, and back to the tool for elite system administrators

Perl is here to stay at least for the community of elite Unix sysadmin (which is a large community and it is the community in which Perl started), because it is a natural fit. It was created by a sysadmin and carry a lot of commonality with classic Unix tool set. And first of all with Unix shell, which is the language which all sysadmin known and use.  In this respect it beats Python and Ruby hands down. Both Python and Ruby also carry too heavy OO baggage and that's also diminishes their value as sysadmin tools -- only few tasks in system administration area can benefit from OO approach. You can appreciate Perl more (and also see Python more realistically despite all hype) if you try to write a couple of utilities for sysadmin work in Python.  Then you would instantly understand how fake are cries about Python superiority over Perl. At least in this particular domain.  Languages are really similar in power, but Perl 5 is much more convenient to use despite worse type system, necessity to put  semicolons at the end of statements and other annoyances.  Another thing that you will understand is that claim that Python is  orthogonal and Perl is baroque language is not quite true. Python pushed a lot of complexity into modules/libraries (which are extremely baroque and some of them badly architectured) and that backfired. It also discard several typical for people who program in C constructs (no C-style for loop; no  ++ and --  for no obvious reason.) That reminds me idiotism of some language construction decisions in Pascal which has for loop with increate one and only one ;-) And several popular construct of Perl are not very well emulated in Python. We can start with double quotes, concept of "undef", etc :-) . Neither language cal be mastered in full by mere mortals: you always use some subset and need to consult documentation each time you use some rarely used part of the language.  and  re-learn it again and again.  And Python related OO-hype is what it is -- hype -- OO does not help much in writing system programs.  Modules and explicit  control over namespaces are two things that usually all you need  and want.

Now the idea of Perl 6 is dead, it mutated is the separate  language (Roku) and that's good. One can see that in Perl 6 OO zealots prevail over  more  cooler heads and it try to use paradigm used in Python and Ruby  competing with  them in the same space. Looks like Larry Wall bough OO hype "hook, line and sinker", and that was a questionable decision, making  Perl 6 "Jonny come lately" in this category.  There were several much simpler areas were Perl 5 could be more profitably be extended such as exceptions, coroutines and, especially, introducing types of variables (forced conversion based on operator used (borrowed from Unix shell) is probably one on the most serious problems with Perl 5, and it definitely inferior to "lazy types" used n Python, when a variable carries its type after the initial assignment (but Python fall into other extreme -- it prohibited automatic conversion even in cases when it is relatively safe.) Actually static types are even better that lazy typing  and that's what should be used (GO has static  types and now eats Python lunch rising  to the top three in GitHub). 

OO does not matter much for writing system utilities, because in this case (unlike say GUI with multiple windows) there no useful application of the concept of class with multiple instances. It is also sad that Larry Wall also did not realize that Javascript prototypes based OO model is a much better implementation of OO then Simula-67 model.

In any case Perl 5 modules do 80% of what is useful in classes (namely provide a separate namespace and the ability to share variables in this namespace between several subroutines) without any OO. If you wish, a primitive constructor  that initialize variable (for example state variables) can be implemented as a BEGIN block.  And for a medium to large programs the control of the namespace is what matters most.

This synergy with Unix shell and access to Unix API alone makes Perl preferable language for writing small utilities which can help of automate sysadmin tasks -- the main use of any scripting language for sysadmins. As it is partially was created as an attempt to merge shell and AWK on a new level it has strong conceptual linkage to bash.  It is , essentially Borne shell that would be created if  Stephen_R._Bourne  was replaced by the developers of AWK ;-)

As of 2019 Perl remains one of the major  scripting languages and has probably the second largest amount of production code running of any scripting language, although most of it was written a while ago. It is not that visible on GitHub, but you understand that Github store many vanity and dead projects, so total muber of project using particular language does notmatter much. Only projects with 100 or more stars matter. Outside system administration, few large system development projects now use Perl ( bioperl.org was probably the last large project of this type and it is gradually is replaced by biopython). In the past several large Web sites such as Yahoo and Amazon used Perl as the programming language. 

Perl no longer is used much for Web development, but the level of suitability to sysadmin tasks was and remain unsurpassed.  Because Python is used in Universities for teaching programming it became more popular for sysadmin tasks as well, but Perl in this niche still is superior to any viable alternative including Python.   So Python ascendance was not only due to the quality of the language and its implementation, but also due to so called "Peter Naur effect":  Peter Naur (of Algol 60 report and BNF notation fame) in his 1975 lecture  "Programming languages, natural languages, and mathematics" which later was reprinted in hypothesized that since late 70th  only those future languages what  can be thought to beginners have changes to enter the "main" programming languages space. All others are limited to niche applications.  In this sense Perl is a clear violation of Peter Naur hypothesis ;-).

Anther important factor in Perl success is that Perl is a very interesting language with highly unorthodox design, which despite its warts produced a lot of innovative, even for this day concepts. As such it is attractive to elite programmers and system administrators who can master the language complexity and benefit form its expressiveness. For example it is one of the few scripting languages which has concept of pointers as a data type, much like C. Also it is unique in a sense that has explicit directives (package) for managing namespace. Not to say an excellent access to Unix internals (Larry Wall was a "superstar" Unix system administrator and it shows)

Perl also has several very well written textbooks although latest popular O'Reilly books are mostly junk as they were captured clueless OO advocates (see Perl for system admins for extended discussion). Perl pioneered huge testing suit for the language and is very stable.   Versions 5.8.8 used in older Linux version (like RHEL 5) and version 5.10 that is used on many current Linux distributions are very stable indeed. Version 5.10 is preferable as it introduced several new features useful for sysadmin tasks and first of all state variables -- variable that can be declared in subroutines but which behave like static variable and are not reinitialized on entry to the subroutine.   Also strict mode helps to cope with the problem of contextual declaration of variables, which the source of nasty and difficult to find errors as misspelled variables are viewed as just another variable with the default initial value.

Perl script can be writing in a way when they are transparent, readable and manageable. No less so then Python scripts which typically suffer from the abuse of OO. The pervert trend of some Perl guru to push to the limit expressiveness of Perl and used difficult to comprehend idioms should be resisted.  Actually if you look at Larry Wall early scripts in Perl 4 he also abused this capability of the language, but he can be excused as a designed of the language. But people like Randal L. Schwartz who make the abuse of language expressiveness a semi-legitimate "Perl Guru" style which gave Perl a bad name should be condemned and never followed.  Here I am reminded Talleyrand advice to young diplomats "First and foremost not too much zeal".

This is a very limited effort to help Unix sysadmins to learn of Perl. It is based on my FDU lectures to CS students.   See also my ebook Introduction to Perl for Unix system administrators It discuss an approach to programming known as "defensive programming" and limits  exposure of Perl to a subset of Perl which can be called "Minimal Perl". Which is only logical as this site explicitly condemns and tries to counter "excessive complexity" drive that dominates many Perl-related sites and publications. 

For sysadmins Perl hits a "sweet spot": (a) it is available on for all Linux distributions (it is important as often in large corporate environment installation of additional languages is prohibited by the security department); (b) it integrates very well (I would say amazingly well)  in the shell environment; (c) it easily replaces multiple utilities (sed, awk, bash for longer scripts, etc.) and is uniform between different flavors of Unix solution; (d)  there are modules to interact with the entire application stack including databases.

One important advantage of Perl over Python is that is very close to shell and programming skills for shell can be reused in Perl; no so much in Python which stems from European school of language and compliers represented by Nicklaus Wirth.   Also Perl also significantly faster then Python, which carry the burden of object orientation even to single variables (creating for each of them something like inode) although on modern CPUs and for the tasks of writing utilities this is critical only for a few tasks (log processing tasks is one example). 

And if one think that Python is a "regular language" I can tell you that it is not. For example variables in Python are treated in C/Perl style -- assignment creates a copy of the variable.

a=3
b=a
a=5 # at this point b is still equal 3, like in Perl 

But for arrays and other "compound objects" this is not the case:

alist = [25,50,75,100]
blist = alist # here Python copes the reference, not the array. so change arlist[0] actually changes blist[0] too

The same is true about overall complexity of the language. The complexity of Python was just pushed into modules, it did not disappeared. And for example for string processing Python is more complex and less expressive language then Perl in which most text processing is done via regex engine.  For example, Python does not  have anything close in convenience to double quoted literals with interpolation until Python 3.6.  Only in Python 3.6+ you have something similar with f-strings:

#!/bin/env python3

job  = 'foo'
cpus = 3
print(f"job {job}")
print(f"cpus {cpus}")

In older versions of Python you need to use C-style strings with % macros. And the best way to imitate Perl/shell double quoted string changes with each major version of Python (String interpolation - Wikipedia), which tell you something about consistency:

# in all versions
   apples = 4
   print("I have %d fruits" % apples)           # implementation via % operator; no longer recommended
   print("I have %(apples)d fruits" % apples )  # name of the variable is allowed; no longer recommended

# with Python 2.6+
   print("I have {0} fruits".format(apples))    # do now this is a method
   print("I have {a} fruits".format(a=apples))  # names instead of positional numerics

# with Python 2.7+
   print("I have {} fruits".format(apples))     # positional value now can be omitted
# with Python 3.0+
    from string import Template
    s = Template('I have $frutno fruits')      # The template object
    s.substitute(frutno=apples)                # actual substitution

# or with Python 3.6+
   print(f"I have {apples} apples")             # radically new implementation based on f-string

If you want interpolation in HERE strings in Perl you do not need to do anything special -- its automatic. But with Python only version 3.6+ has some analog called triple-quoted f-string:

cpus = 3
job  = 'foo'
print(f'''\
job {job}
cpus {cpus}''')

And if you you think that Python is logical original language superior to Perl I have a Brooklyn  bridge to sell to you. For example in Python search of the string can be performed with find method (C programmers and Perl users be  damned):

message = "hello world"
pos = message.find("lo")
print(pos)
If the substring is not present, find returns a value of -1 like index function in Perl.  But the find() method should be used only if you need to know the position of the substring. To check if substring is present in the string in  conditional expression you need to use the in operator. And there is also index function in Python that behave differently, just to make C -programmers crazy ;-) It throws exception if the substring is not found.  This incompatibility suggests that Python designers have very little knowledge/respect of Unix and C when they started their project.

Moreover, if one wants to to calculate the length of the string in Python, he/she needs to use len function, not length method as one would expect.

message = "hello world"
mlen = len(message)
And such "non-uniformities" and special cases are all over Python language.  Also the mere number of methods provided in for each type is overwhelming in Python. For example there are 37 (thirty seven) string methods. Perl has just a dozen string functions. Everything else is done via regular expression. Strings in Python are immutable which create performance penalty.

Evolution of Perl

Despite the slide in popularity Perl experienced since 2000 Perl and severe lack of resources for the development of the language, Perl continues to evolve and improve. Thankfully it evolves slowly, but during the last decade we got state variables (5.10) and a couple of other useful features. Along with  several useless features or features that  which many would consider redundant or even harmful and that should probably be removed from the language. The latter is due to the fact that after the create of the language steps down there is no high authority to "bless" changes for conceptual integrity. And petty people with high opinion about themselves and pretentions to become high priests of the community try to make their "scratch" by spoiling the language :-(.  This is a common, well known  problem with large open source project is which original developer stepped down and it is not limited to Perl. It is often described under the title "the loss of conceptual integrity" *the term introduced in the The Mythical Man Month by Fred Brooks. Different manifestation of the same are also known  Software Peter principle Software entropy  and  Featuritis

So far the evolution of Perl failed to resolve the most obvious problem with the language such as

Contrary to popular opinion the use of sigils in Perl is more or less logical especially for scalar variables. Sigil $ denotes derefercing. It is also undeniable that string interpolation inside double quoted string is easier with sigils. Moreover sigils also clearly demarcate variables from built-in functions and subroutines  making wting syncax coloring in editors easier.  So this particular decision withstand the test of the time.

Contrary to popular opinion, syntax of Perl 5 is pretty regular, and closely adheres to traditional C-style syntax which makes it easy to learn for both sysadmin coming from BASH or ksh and C or C++ programmers coming from respective language.  It can favorably compared with the disaster which is syntax of Borne shell.

Actually it does not  look too bad in comparison with Python which has syntax rules which are much farther from C and Unix. Python creates severe cognitive dissonance for people who program in C or C++. Especially with some decisions like usage of whitespace to determine the nesting. This decision  has serious negative effects for long multipage loops and other control constructs, forcing to make them shorter.   Not that C-style solution used in Perl is perfect (runaway unclosed '{' bracket is a huge problem with this notation), but at least it is uniform with C and C++, which is important. People who spend many years programming C or C++ have their own methods to compensate for the deficiency of this notation and accumulate tremendous skills of reading it and using it large programs. Experience that Python just sends to the dust bin.

Somehow due to his natural talent (he was never trained as a compiler writer and does not have CS degree) Larry Wall managed to avoid most classic pitfalls in creating of the syntax of the language, pitfalls in which creators on PHP readily fell ("dangling else" in PHP is one example) and from which Python suffers as well.

Just as a side note Python inherits from C usage of = for assignment and == for comparison, the blunder that has very serious consciences as for the amount of errors both in C and Perl. In Python assignment is invalid in conditional expressions, which makes it safer and eliminates this type of errors, but at the same time losing expressive power and making programs more verbose:

   if a=1 : print a
        ^
SyntaxError: invalid syntax

Perl debugger is one of better kept secrets of the language. It is an amazingly powerful tool

One of Perl’s better-kept secrets is its built-in debugger that allows developers to test their programs with ease and to rapidly track down errors in their Perl scripts. Python only recently got a semi-decent debugger. Before that the language sucked badly. PHP is another similar sicker. Actually for qualified programmer the quality of the debugger is as important if not more important then the quality of the language. In this area Perl really shines as it has powerful debugger as long as I remember (it did have it in 1994 when I started to use it)

This is a very powerful tool that unfortunately few Perl programmers (and even fewer sysadmins)  know well. It allows to create debugging scripts, create you own set of aliases for each program you debug, as well as remote debugging.  I view it a crown jewel of the Perl language environment.

While number of IDE that Perl has is less then Python you can use free Komodo editor (somewhat buggy and idiosyncratic, but OK) or  pycharm  which does not advertize its support of Perl but does it really well (and it has a free version for individual developers).  Eclipse has Perl plug-in as well.  all of them integrates with  Perl debugger.

I think the second book about the language you should read should be a book about Perl debugger (see below)

Perl is installed by default in all flavors of Linux and all other enterprise flavors of Unix (Solaris, HP-UX and AIX)

While Python is not installed by default in all major Linux distributions  too, this is not true for AIX, Solaris and HP-US.  And in highly secure environment you are prohibited installing such huge packages without jumping via so many bureaucratic hoops that you regret that you started this adventure.

Systems administrators need to deal with many repetitive tasks in a very complex, and changing environment which often includes several different flavors of Linux (RHEL and Suse) and Unix (Solaris, HP-UX and AIX). Linux has Perl installed by  default.  It is also included in all major Unix flavors but version installed might be outdated and need upgrading. For example Oracle installs Perl too, so it is automatically present on all servers with Oracle database.  Some other application install Perl too.  That means that it provides the simplest way to automate recurring tasks on multiple platforms. Among typical tasks which sysadmin need to deal with:

You definitely can greatly simplify your life as well as improve "manageability" of the servers (or group of servers) with additional Perl scripts, some written by use, some borrowed and adapted to your environment.  As long  as you still apply KISS principle and do not try to overload those scripts with "features".  Because at some point the task of maintaining the scripts became evident and unless scripts are simple the game might not worth the candles.   that's the gotchas, which catches many  sysadmin  who overreached  and added too much complexity to their scripts.  The slogan KISS can be in this contest mean: keep it simple sysadmin.

As most sysadmins already know shell, the affinity with shell is one of the major advantages of using Perl as the second scripting language for Unix sysadmin. no other language come close in this respect: Perl allow to reuse most of the key concepts of the shell.

What Softpanorama can offer to sysadmins who want to learn Perl

IMHO the main advantage of using powerful complex language like Perl is the ability to write simple programs which in the past required for sysadmin to use several languages (bash+AWK+SED). It also was created without OO which later was "bolted on". And I consider this a very important advantage for sysadmin domain of utilities. Perhaps the world has gone overboard on this object-oriented thing.  I do not see much use of it for utilities space -- they add nothing and the attempt to structure utilities in OO fashion typically backfires and leads to excessive complexity and bloat. Often it leads to the creating what is called "object oriented spaghetti".

At the same time Perl is surprisingly high level language and for writing sysadmin utilities is has higher level then Python. You do not need many tricks used in lower level languages as Perl itself provides you high level primitives for the task.

This page is linked to several sub-pages in the top "contents" table. The most important among them are:

All language have quirks, and all inflict a lot of pain before one can adapt to them. Once learned the quirks become incorporated into your understanding of the language. But there is no royal way to mastering the language. The more different is one's background is, more one needs to suffer. Generally any user of a new programming language needs to suffer a lot ;-)

Adapting to the language quirks and warts

When mastering a new language first you face a level of "cognitive overload" until the quirks of the language become easily handled by your unconscious mind. At that point, all of the sudden the quirky interaction becomes a "standard" way of performing the task. For example, regular expression syntax seems to be a weird base for serious programs, fraught with pitfalls, a big semantic mess as a result of outgrowing its primary purpose. On the other hand, in skilled hands this is a very powerful tool that can serve a reliable parser for complex data and in certain cases as a substitute for string functions such as index and substr.

There are several notable steps in adaptation to Perl idiosyncrasies for programmers who got used to other languages:

  1. Missing semicolon at the end of statement. This is a typical problem for all languages that delimit statements with the semicolon. There is something unnatural to humans in this arrangement. It looks to me that Fortran approach (statements ends at the end of the line unless the line contains  \ at the end is a better deal.  IBM PL/1 debugging  complier  designers (one of greatest teams ever to design compilers)  implemented the idea of "soft semi-colon" -- if the insertion of semicolon allow to continue parsing then correct  this error and inform the user. But this was during the day of batch compliers and this approach has its own  drawbacks, as it can introduce errors to the program due to automatic correction.

    The problem is that this error is persistent and continue to occur for highly qualified users of Perl with amazing and consistent regularity. Multiple years of using the language under the belt does not help.  One way to lessen this problem is to check for it before you submit  the script to the interpret.  Prettyprinter can label such line  too if you have your custom Prettyprinter (I have)
     
  2. Forgetting to put $ in front of scalar variable. This problem is aggravated if you use several language with the other that does not require this prefix. One early sign is when you start to put $ on all scalar variables automatically.  C programmer can think about $ as as a dereferencing operator to the pointer to the value of the variable. So if line is as pointer, then $line is the value of the variable referenced by this pointer.  and $$line is the second level dereferencing.

    That's easy for those people who use write their own shell scripts and generally is not a problem for sysadmins. Most mistakes when you omit $ in front of the variable are diagnosed by interpreter, but some cases like $location{city} are not. The problems arise if  along with Unix shell you use the third language, for example C.  In this case you automatically makes make mistakes, despite your experience, and you need conscious effort to avoid them all the time. This is the case with me.
     

  3. Using two different comparison operations, one for strings and the other for numerical values ("==" for numbers vs. eq for strings) for comparison numbers and strings.  This is design blunder Perl inherited from Unix shell.  That also makes operation "typed", which is an interesting, but very questionable approach inhereted by Perl from Shell. The problm is that the game is not worth candles -- practice convincingly had shown that this adds very little to the language power and expressivness,  but introduces nasty bugs and it is better to allow only explicit type conversions.  In case a constant is involved ( like $line == 'EOF' ) Perl provides warnings, but if two variables are involved, the interpreter does not provide any warnings, so you need to be very careful.

    Especially if you use other language in parallel with Perl. In this case such errors crop into your scripts automatically. Only if one of the operators of "==" is a string constant, meaningful automatic diagnostic can be provided.
     

  4. Use of "=" as equality predicate for numbers instead of ==. If you use and C-style which uses "=" for assignments you are in trouble: you can easy make an error using it instead of == in conditional. Please note that Algol60 avoided this by using := for assignment, so even early languages recognized this problem., So in away this can be viewed as a blunder in C-language design (or more correctly in PL/1 language design as C for all practical purposes is just a subset of PL/1 with pointers; and it was designed as such (PL/1 was system programming language for Multics what was the major school of programming for Thomson and Richie) 

    The pitfall of using "=" for assignment,  results in the side effect of introducing errors in comparisons in Perl, as you put "=" instead of "==".  For example,    if ($a=1)...  instead of if  ($a==1)... This problem was understood by designers on Algol 60 ( To avoid it they used := for assignment instead of plain =), which was designed is late 50th. But Perl designers followed C designers (which make this blunder, along with several other in designing C)  and naturally stepped on this rake again. With predictable result. Actually the designers of Fortran, PL/1, C (as derivative of PL/1), C++ and Java ignored this lesson (Fortran designers are actually not guilty as it predates Algol 60). But  because C  (with its derivatives such as C++ and Java) became dominant programming language we have, what we have: propagation of this blunder to many top programming languages. Now think a little, about the notion of progress in programming language design ;-)  It's sad that the design blunder about which designers knew 65 years ago still is present in the most popular languages used today ;-). In all languages that have lexical structure of C, this blunder remains one of the most rich source of subtle errors for novices. Naturally this list includes Perl. C programmers typically are already trained to be aware about  this language pitfall. But in Perl you too can use several protective measures
    1. Modify syntax highlighting in your editor  so that such cases were marked in bold red.
    2. Manually or automatically (simple regex done in the editor can detected ~ 99% of cases) reorganize such comparisons
    3. Put the constant on the left part of comparison, like in  if (1==$a)....
    4. Recent versions of Perl interpreter provide warning in this case, so checking your script with option -cw  or better using use warnings  pragma in all your scripts. It also helps if IDE provides capability to display of results of checking of syntax in one of the windows and jump to the line in code listed in the error or warning (this is a standard feature of all IDEs and actually this can be done in most editors too). 
  5. Missing closing "}" problem . This problem is typical for all C-style languages and generally requires pretty printer to spot.  But Perl interpreter has a blunder -- it does not recognize the fact that in Perl subroutines can't be nested within blocks and does not point to the first subroutine as the diagnostic point -- it points to the end of the script.  Usually you need a Prettyprinter to spot this error. In you do notr have one and do not  want to get one and learn to use it (big mistake) one of the best way to find exact point of this error is to extract suspicious section into a new file and check it separately, cutting not relevant parts, until you detect the problem. The longer the program is the more acute this problem becomes. BTW this problem was elegantly solved in PL/1 which was created in early 60th: PL/1 has labels for closing statements as in "mainloop: do... end mainloop" which close all intermediate constructs automatically. Both C and Perl failed to adopt this innovation.  Neither Perl not C also use the concept of Pascal "local numeric labels"  -- labels that exist only until they are redefined, see discussion at Knuth.

    I would way that the lack of build-in Prettyprinter in Perl is a blunder of the designers of Perl interpreter. It is understandable as Perl never enjoyed sizable material support from big corporations, but still...
     

  6. Missing round brackets  or unbalanced round brackets  in control statements like if, while, etc . Like "missing ';' " problem this error is persistent and does not evaporates with the increate of your Perl skills. Looks like this is a design flow of the language and you need to check you scripts for this particular error manually. Good Prettyprinter can point most of those errors because  they are more local than missing "}" error.
     
  7. Missing " (double quote) or ' (single quote) problem.  With good editor this is not a problem as syntax highlighting points you where the problem begins.  Perl has pragma of specified max constant length, which is one way to improve quality of detection of this error. You can also implement  program (one line sting literals only) in the interpreter, because multiline strings pretty rate in real programs.  To put multilateral string you can need to disable this pragma for the  fragment of the script where it is located.
  8. Typos in variables which creates variables used only once.  You can block this  error now with strict pragma, so it is less important unless yyou need to maintain huge legacy scripts.  Also Perl interpreter provides warnings for all such cases.  Looks like that requrement to declare all variables before use is a sound programming language design practice.  The gains from contextual  typing of variables (introduced BTW in Fortran)  do not compensate the damage from such an error.

Please note that as syntax of Perl is complex. So the diagnostic in Perl interpreter is really bad and often point to the spot far below where the error occurred.  It is nowhere near the quality of diagnostics that mainframe programmers got in IBM PL/1 diagnostic complier, which is also probably 50 years old and run on tiny by today standard machines with 256K (kilobytes, not megabytes)  of RAM and 7M (megabytes, not gigabytes, or terabytes) harddrives.  The only comfort  is that other scripting languages are even worse then Perl ;-).

Benefits that Perl brings to system administration 

All-in-all Perl is the language that fits most sysadmin needs, It' not fancy and its general usage is in decline since 2000 but fashion should never be primary factor in choosing the scripting language. Perl has stable and well tested  interpreter and is close to shell (to the extent  that most concepts of shell can be directly reused). And that's what important. As on modern servers Perl interpreter loads in a fraction of a second, Perl also allows to get rid of most usage of AWK and SED, making you environment more uniform and less complex. This is an important advantage.  Among benefits that Perl bring to system administration are

In short if make sense to learn Perl as it makes sysadmin like a lot easier. Probably more so then any other tool in sysadmin arsenal...

Perl is really great for text processing and in this particular domain is probably unmatched. For example in Python regular expressions are implemented via standard library module; they are not even a part of the language.

A warning about relative popularity

 As of 2017 Perl no longer belongs to the top 10 programming languages (Scripting languages slip in popularity, except JavaScript and Python, Infoworld, Nov 13, 2017).  It's still more popular then Visual Basic, so there nothing to worry about.  But far less then popular then Python.  Of cause popularity is not everything. Python and Perl share some characteristics, but don't exactly occupy the same niches. But it is a lot: fashion rules the programming, so this is a factor that you need consciously evaluate and be aware of.

In large enterprise environment, outside system administration area Perl now is almost invisible. Python is gaining ground in research. Mostly because universities both in the USA and Europe now teach Python in introductory classes and engineers come "knowing some Python". This looks like "Java success story" of late 1990th on new level. Like Perl, Python is also now installed on all Linux distributions by default and there are several important linux system programs written in Python (yum, Anaconda, etc) which implicitly suggest that Python has Red Hat mark of adoption/approval too (yum was originally written at Duke University Department of Physics)

So there is now a pressure to adopt Python. That's sad, because IMHO Perl is a great scripting language which can be used on many different levels, starting from AWK/SED replacement tool (this especially make sence if you use different platforms. for example their behavior differs between Mac OS X and Linux. But PERL is the same in both those environments.). Going from Perl to Python for text processing to me feels like leaving a Corvette and driving a station wagon. Python will gets you there. But it's not fun and will take more time although you probably might feel more comfortable inside.

Here is an insightful post on this topic (Which is better, Perl or Python Which one is more robust How do they compare with each other):

Joe Pepersack, Just Another Perl Hacker Answered May 30 2015

Perl is better. Perl has almost no constraints.  It's philosophy is that there is more than one way to do it (TIMTOWTDI, pronounced Tim Toady). Python artificially restricts what you can do as a programmer.  It's philosophy is that there should be one way to do it.   If you don't agree with Guido's way of doing it, you're sh*t out of luck.

Basically, Python is Perl with training wheels.   Training wheels are a great thing for a beginner, but eventually you should outgrow them.  Yes, riding without training wheels is less safe.   You can wreck and make a bloody mess of yourself.   But you can also do things that you can't do if you have training wheels.   You can go faster and do interesting and useful tricks that aren't possible otherwise. Perl gives you great power, but with great power comes great responsibility.

A big thing that Pythonistas tout as their superiority is that Python forces you to write clean code.   That's true, it does... at the point of a gun, sometimes at the detriment of simplicity or brevity.   Perl merely gives you the tools to write clean code (perltidy, perlcritic, use strict, /x option for commenting regexes) and gently encourages you to use them.

Perl gives you more than enough rope to hang yourself (and not just rope, Perl gives you bungee cords, wire, chain, string, and just about any other thing you can possibly hang yourself with).   This can be a problem.   Python was a reaction to this, and their idea of "solving" the problem was to only give you one piece of rope and make it so short you can't possibly hurt yourself with it.    If you want to tie a bungee cord around your waist and jump off a bridge, Python says "no way, bungee cords aren't allowed".  Perl says "Here you go, hope you know what you are doing... and by the way here are some things that you can optionally use if you want to be safer"

Some clear advantage of Perl:

Advantages of Python

IDE that you can use with Perl

Usage of IDE is a must in the current environment. Often sysdmins neglect this, but it does diminished their productivity. the key here is a powerful editor, built-in  remote debugger  while nice is not absolutely necessary. But ability to compare two versions, show usage of particular variable and prompt for the  write variable when writing statements are important. Show of nesting and pretty printing are also important but  can be done with the external tools.  Also important is the  ability to work with data-space (renaming varibale in files for the whole project, etc). Perl does not even ship with the "Standard IDE". But there are several usable options:

  1. Paradoxically GVIM is not that bad and can be installed both on Windows and Linux. 
  2. Padre, which is somewhat competitive with Komodo is available for free. The problem is that  but the latest binary distribution suitable for beginners is from 2012. It's still highly usable.
  3. Komodo Edit can serve as a surrogate IDE too. It is a decent editor and for Perl I would rate it slight higher then Notepad++. It does a couple slick things: support macros and support syntax checking.  
  4. pycharm -- the most popular Python IDE can work with Perl and works well. Attractive if you use some Python.  
  5. Eclipse via Perl plug-in.
  6. Visual Studio, if you already use it for other projects.  Adding Visual Studio editor support for other languages Microsoft Docs See also

My feeling is that for Perl to remain competitive IDE should be maintained and shipped along with Perl interpreter (like in Python and R distributions).  May be at the expense of some esoteric modules included in standard  library.

Books to read

Python now dominate books  on scripting languages and  number of books per year devoted to Python and available via Amazon for 2017 is at least one order of magnitude larger then the number of books devoted to Perl (quality issues aside). All this creates a real pressure to use Python everywhere, even in system administration.  But first of all very few Python books  are good. Most do not explain the language well. And the second  is that you need just a couple of them not a dozen. So while on number front Perl definitely can't compete with Python several quality books (most not from O'Reilly) are available.  i would recommend (Recommended Perl Books)

The most common versions of Perl  5 in production

RHEL 6.x now ships with Perl 5.10. Many classic Unixes still ship with Perl 5.8.8. Older versions of  Solaris and HP-US servers might have version below Perl 5.8.8 but in 2017 that's rare as most of such servers are decommissioned (typical lifespan of a server in corporate environment is 5-7 years). 

It you need compatibility with all major flavor of Unix in you scripts it is a safe bet to write for Perl 5.8.8. Such a decision virtually guarantee compatibility with all enterprise servers, except those that should be discarded 5 or 10 years ago. In other words no "state" variables, if you want "perfect" compatibility. Non perfect, but acceptable.

If you need only Linux deployment compatibility that can be achieved by using version 5.10 which allow you to use "state" variables.

If you need compatibility with linux servers only version 5.10 look like a more or less safe bet too (very few enterprise servers in 2017 are now below version RHEL 6; those typically have Perl 5.8). 

Also too high version of Perl 5 is actually not desirable --  see note about Perl 5.22. (the current version of Perl 5 is version 30).  Hopefully warts added to version 22  will be corrected based on the feedback. Here is a slide from Oct 3, 2016 by Tom Radcliffe The Perl Paradox

The problem of Perl complexity junkies

There is a type of Perl books authors that enjoy the fact that Perl is complex non-orthogonal language and like to drive this notion to the extreme. I would call them complexity junkies. Be skeptical and do not take recommendations of Perl advocates like Randal L. Schwartz  or Tom Christiansen for granted :-) Fancy idioms are very bad for novices. Please remember about KISS principle and try to write simple Perl scripts without complex regular expressions and/or fancy idioms. Some Perl gurus pathological preoccupation with idioms is definitely not healthy and is part of the problem, not a part of the solution...

We can defines three main types of Perl complexity junkies:

My issues with Perl is when people get Overly Obfuscated with their code,
because the person thinks that less characters and a few pointers makes the code faster
.

Please remember about KISS principle and try to write simple Perl scripts without overly complex regular expressions or fancy idioms.  If you do this Perl is great language, unmatched for sysadmin domain. Simplicity has great merits even if goes again current fancy.

Generally the problems with OO mentioned above are more fundamental than the trivial "abstraction is the enemy of convenience". It is more like that badly chosen notational abstraction at one level can lead to an inhibition of innovative notational abstraction on others. In general OO is similar to idea of "compiler-copiler" when you create a new language in such a way that it allow to compile new constructs with the existing complier.  While in some cases useful or even indispensible, there is always a price to pay for such  fancy staff.

Tips

Detecting missing semicolon problem in Perl

Some deficiencies of Perl syntax were directly inherited from C. One of the most notable "obligatory semi-colon after ach statement. Which lead to tremendous amount of errors. You can use "soft semicolon" approach (implied semicolon on line end if round brackets or similar symmetrical symbols are balanced) and put semicol on each line and then depete it on a fewline that do not need it

It is eady to implement using any editor maro (for example in vi) or as a mode of the pretty printer.

Such an approach cuts number of iteration required to get rid of syntax errors by two or three.

Avoiding mistyping "=" instead of "==" blunders by reversing comparison with the constant

One of most famous C design blunder was the introduction of a small lexical difference between assignment and comparison (remember that Algol used := for assignment; PL/1 uses = for both) caused by the design decision to make the language more compact (terminals at this type were not very reliable and number of symbols typed matter greatly. In C assignment is allowed in if statement but no attempts were made to make language more failsafe by avoiding possibility of mixing up "=" and "==". In C syntax if ($a = $b) assigns the contents of $b to a and executes the code following if b not equal to 0. It is easy to mix thing and write if ($a = $b ) instead of (if ($a == $b) which is a pretty nasty bug. You can often reverse the sequence and put constant first like in

if ( 1==$i ) ...
as
if ( 1=$i ) ...
does not make any sense, such a blunder will be detected on syntax level.

Locating unbalanced "}" errors using pretty printer

This is the problem with all C-style language not only Perl. Ruby managed to avoid it switching to Algol-style delimiters, Typically this is connected with your recent changes so you should know where to look. Pretty printer (even simplistic Neatperl) allows instantly detent this type of errors

If you do not access to any pretty-printer (a very sad situation indeed) use diff with the last version that complied OK (I hope you use come kind of CMS like subversion or git)

The optimal way to spot missing '}' is to use pretty printer. In the absence of pretty printer you can insert '}' in binary search fashion until you find the spot where it is missing.

You can also extract part of your script and analyze it separately, deleting "balanced" parts one by one. This error actually discourages writing very long "monolithic" Perl scripts so the is a silver lining in each dark cloud.

You can also use pseudo comments that signify nesting level zero and check those points with special program or by writing an editor macro. One also can mark closing brackets with the name of construct it is closing

if (... ) { 

} # if 

Problem of unclosed quote at the end of the line string literal ("...")

Use a good editor. moreover often you can split long literals into one line literals and concatenate them with dot operator. Perl process those at complite time so there is not run-time hit for using this (and it should not be for any other language with a decent complier -- this complier optimization is classed constant folding and is a standard in modern compliers).

As a historical note specifying max length of literals is an effecting way of catching missing quote that was implemented in PL/1 compilers. You can also have an option to limit literal to a single line. In general multi-line literals should have different lexical markers (like "here" construct in shell). Perl provides the opportunity to use concatenation operator for splitting literals into multiple line, which are "merged" at compile time, so there is no performance penalty for this constructs. But there is no limit on the number of lines string literal can occupy so this does not help much. If such limit can be communicated via pragma statement at compile type in a particular fragment of text this is an effective way to avoid the problem. Usually only few places in program use multiline literals, if any. Editors that use coloring help to detect unclosed literal problem but there are cases when they are useless.

How to avoid using wrong comparison operator comparing two variable

If you are comparing a variable and a constant Perl interpret can help you to detect this error. but if you are comparing two variable you are on your own. And I often use wrong comparison operator just out of inertia or after usage of C. the most typical for ma error is to use == for stings comparison.

One way is to comment sting comparisons and then match comments with the comparison operator used using simple macro in editor (you should use programmable editor, and vim is programmable)

Usage of different set of comparison operator for number and string comparison is probably the blunder in Perl design (which Python actually avoided) and was inherited from shell. Programmer that use other languages along with Perl are in huge disadvantage her as other language experience force them to make the same errors again and again. Even shell solution (using different enclosing brackets); it might well be that in Perl usage of ( ) for arithmetic comparison and ((...)) for string would be a better deal. They still can be used as a part of defensive programming so that you can spot inconsistencies easier

Perl as a new programming paradigm

Perl + C and, especially Perl+Unix+shell represent a new programming paradigm in which the OS became a part of your programming toolkit and which is much more productive for large class of programs that OO-style development (OO-cult ;-). It became especially convenient in virtual machine environment when application typically "owns" the machine. In this case the level of integration of the language and operating system became of paramount importance and Perl excels in this respect. You can use shell for file manipulation and pipelines, Perl for high-level data structure manipulation and C when Perl is insufficient or too slow. The latter question for complex programs is non-trivial and correct detection of bottlenecks needs careful measurements; generally Perl is fast enough for most system programs.
Exploiting high level of integration of Perl with shell and Linux is a new programming paradigm which became especially convenient in virtual machine environment when application typically "owns" the machine. In this case the level of integration of the language and operating system became of paramount importance and Perl excels in this respect. In a way it is similar to LAMP paradigm.

The key idea here is that any sufficiently flexible and programmable environment - and Perl is such an environment -- gradually begins to take on characteristics of both language and operating system as it grows. See Stevey's Blog Rants Get Famous By Not Programming for more about this effect.

Any sufficiently flexible and programmable environment - and Perl is such an environment -- gradually begins to take on characteristics of both language and operating system as it grows.

Unix shell can actually provide a good "in the large" framework of complex programming system serving as a glue for the components.

From the point of view of typical application-level programming Perl is very under appreciated and very little understood language. Almost nobody is interested in details of interpreter, where debugger is integrated with the language really brilliantly. Also namespaces in Perl and OO constructs are very unorthodox and very interesting design.

References are major Perl innovation

References are Perl innovation: classic CS view is that scripting language should not contain references (OO languages operate with references but only implicitly). Role of list construct as implicit subroutine argument list is also implemented non trivially (elements are "by reference" not "by name") and against CS orthodoxy (which favors default "by name" passing of arguments). There are many other unique things about design of Perl. All-in-all for a professional like me, who used to write compilers, Perl is one of the few relatively "new" languages that is not boring :-).

Never forget that Perl has a great debugger

The quality of the debugger for the language is as important as the quality of language itself. Perl debugger is simply great. See Debugging Perl Scripts

Brilliance of Perl Artistic license

Perl license is a real brilliance. Incredible from my point of view feat taking into account when it was done. It provided peaceful co-existence with GPL which is no small feat ;-). Dual licensing was a neat, extremely elegant cultural hack to make Perl acceptable both to businesses and the FSF.

It's very sad that there no really good into for Perl written from the point of view of CS professional despite 100 or more books published.

Perl warts


A small, crocky feature that sticks out of an otherwise clean design. Something conspicuous for localized ugliness, especially a special-case exception to a general rule. ...

Jargon File's definition of the term "wart"

Language design warts

Perl extended C-style syntax in innovative way. For example if statement always uses {} block, never an individual statement, also ; before } is optional. But it shares several C-style syntax shortcomings and introduced a couple of its own:

For a language aficionado Larry Wall make way too many blunders in the design of Perl. Which is understandable (he has no computer science background and was hacker in heart), but sad.

There are also several semantically problems with the language:

Absence of good development environment

R-language has RStudio which probably can be viewed as gold standard of minimal features needed for scripting language GUI. While RStudio has a weak editor it has syntax highlighting and integration with debugger and as such is adequate for medium scripts.

There is no similar "established" as standard de-facto GUI shipped with Perl interpreter and looks like nobody cares. That's a bad design decision although you can use Orthodox file manager (such as Midnight commander, or in Windows Far or Total Commander) as poor man IDE. Komodo Edit is more or less OK editor for Perl and is free although in no way it is full IDE.

This is not a show stopper for system administrators as they can use screen and multiple/different terminal sessions for running scripting and editing them. Also mcedit is handy and generally adequate for small scripts. To say nothing that each sysadmin know badic set of command for vi/vim, and many know it well.

But this is a problem when you try to write Perl scripts with over 1K lines which consist of multiple files. Many things in modern IDE helps to avoid typical errors (for example identifiers can be picked up from the many by right clicking, braces are easier to match if editor provide small almost invisible vertical rulers, color of the string help to detect running string constants, etc.

Currently Komodo and free Komodo editor are almost the only viable game in town.

See

for additional discussion.

Lost development priorities

For mature language the key area of development is not questionable enhancements, but improvement of interpreter diagnostics and efforts in preventing typical errors (which at this point are known).

Perl version 5.10 was the version when two very useful enhancement to the language were added:

Still very little was done to improve interpreter in order to help programmers to avoid most typical Perl errors. that means that the quality of the editor for Perl programmers is of paramount importance. I would recommend free Komodo editor. It allows you to see the list of already declared variables in the program and thus avoid classic "typo in the variable" type of errors.

Not all enhancements that Perl developers adopters after version 5.10 have practical value. Some, as requirement to use backslash in regular expressions number of iterations ( so that /\d{2}/ in "normal" Perl became /\d\{2}/ in version 5.22), are counterproductive. For that reason I do not recommend using version 5.22. You can also use pragma

use v5.12.0

to avoid stupid warnings version 5.20 generates.

There is no attempts to standardize Perl and do enhancements via orderly, negotiated by major stakeholders process. Like is done with C or Fortran (each 11 years; which is a very reasonable period which allow current fads to die ;-). At the same time quality of diagnostics of typical errors by Perl interpreter remains weak (it imporved with the introduction of strict though).

Support for a couple of useful pragma, for example, the ability to limit the length of string constants to a given length (for example 120) for certain parts of the script is absent. Ot something similar like "do not cross the line" limitation.

Local labels might help to close multiple level of nesting (the problem of missing curvy bracket is typical in al C-style languages)

 1:if( $i==1 ){
     if( $k==0 ){
         if ($m==0 ){
   # the curvy bracket below closes all opened clock since the local label 1
 }:1 

Multiple entry points into subroutines might help to organize namespaces.

Working with namespaces can and should be improved and rules for Perl namespaces should be much better better documented. Like pointers namespaces provide powerful facity to structuring language programs. which can be used with or without modules framework. this is a very nice and very powerful Perl feature that makes Perl a class or its own for experienced programmers. Please note that modules are not the only game in town. Actually the way they were constructed has some issues and (sometime stupid) overemphasis on OO only exacerbate those issues. Multiple entry points in procedures would be probably more useful and more efficient addition to the language. Additional that is very easy to implement. The desire to be like the rest of the pack often backfire... From SE point of view scripting language as VHL stands above OO in pecking order ;-). OO is mainly force feed for low level guys who suffer from Java...

Actually there are certain features that should probably be eliminated from Perl 5. For example use of unquoted words as indexes to hashes is definitely a language designers blunder and should be gone. String functions and array functions should be better unified. Exception mechanism should be introduced. Assignment in if statements should be somehow restricted. Assignment of constants to variables in if statement (and all conditions) should be flagged as a clear error (as in if ($a=5) ... ). I think latest version of Perl interpreter do this already.

Problems with Perl 5. 22

Attention: The release contains an obvious newly introduced wart in regex tokenizer, which now requires backslash for number of repetitions part of basic regex symbols. For example in case of /\d{2}/ which you now need to write /\d\{2}/ -- pretty illogical as a curvy brace here a part of \d construct, not a separate symbol (which of course should be escaped);

Looks to me like a typical SNAFU. But the problem is wider and not limited to Perl. There is generally tendency for a gradual loss of architectural integrity after the initial author is gone and there is no strong "language standard committee" which drive the language development (like in Fortran, which issues an undated version of the standard of the language each 11 years).

So some languages like Python this is still in the future, but for many older languages is is already reality and a real danger. Mechanism for preventing this are not well understood. The same situation happens with OS like Linux (systemd).

This newly introduced bug (aka feature) also affects regexes that use opening curvy bracket as a delimiter. Which is a minor but pretty annoying "change we can believe in" ;-). I think that idiosyncrasy will prevent spread this version into production version of Linux Unix for a long, long time (say 10 years) or forever. Image the task of modification of somebody else 30-50K lines Perl scripts for those warnings that heavily uses curvy braces in regex or use \d{1,3} constructs for parsing IP addresses.

This looks more and more like an artificially created year 2000 problem for Perl.

Dr. Nikolai Bezroukov


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Dec 01, 2019] How can I export all subs in a Perl package?

Jan 01, 2009 | stackoverflow.com

Ask Question Asked 10 years, 7 months ago Active 3 years, 5 months ago Viewed 18k times


Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

[Dec 01, 2019] function - How can I export all subs in a Perl package - Stack Overflow

Jan 01, 2009 | stackoverflow.com

How can I export all subs in a Perl package? Ask Question Asked 10 years, 7 months ago Active 3 years, 5 months ago Viewed 18k times


Ville M ,

I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );

Using fully qualified names would require bunch of change to existing code so I'd rather not do that.

Is there @EXPORT_ALL?

I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.

To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).

Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)

brian d foy , 2009-04-08 23:58:35

Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require and everything will be in the current package. Easy peasy.

Michael Carman , 2009-04-09 00:15:10

Don't. But if you really want to... write a custom import that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
    no strict 'refs';

    my $caller = caller;

    while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
        next if      $name eq 'BEGIN';   # don't export BEGIN blocks
        next if      $name eq 'import';  # don't export this sub
        next unless *{$symbol}{CODE};    # export subs only

        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $symbol };
    }
}

Chas. Owens ,

Warning, the code following is as bad an idea as exporting everything:
package Expo;

use base "Exporter";

seek DATA, 0, 0; #move DATA back to package

#read this file looking for sub names
our @EXPORT = map { /^sub\s+([^({\s]+)/ ? $1 : () } <DATA>;

my $sub = sub {}; #make sure anon funcs aren't grabbed

sub foo($) {
    print shift, "\n";
}

sub bar ($) {
    print shift, "\n";
}

sub baz{
    print shift,"\n";
}

sub quux {
    print shift,"\n";
}

1;

__DATA__

Here is the some code that uses the module:

#!/usr/bin/perl

use strict;
use warnings;

use Expo;

print map { "[$_]\n" } @Expo::EXPORT;

foo("foo");
bar("bar");
baz("baz");
quux("quux");

And here is its output:

[foo]
[bar]
[baz]
[quux]
foo
bar
baz
quux

Jon Ericson , 2009-04-08 22:33:36

You can always call subroutines in there fully-specified form:
MyModule::firstsub();

For modules I write internally, I find this convention works fairly well. It's a bit more typing, but tends to be better documentation.

Take a look at perldoc perlmod for more information about what you are trying to accomplish.

More generally, you could look at Exporter 's code and see how it uses glob aliasing. Or you can examine your module's namespace and export each subroutine. (I don't care to search for how to do that at the moment, but Perl makes this fairly easy.) Or you could just stick your subroutines in the main package:

 package main;
 sub firstsub() { ... }

(I don't think that's a good idea, but you know better than I do what you are trying to accomplish.)

There's nothing wrong with doing this provided you know what you are doing and aren't just trying to avoid thinking about your interface to the outside world.

ysth , 2009-04-09 01:29:04

Perhaps you would be interested in one of the Export* modules on CPAN that lets you mark subs as exportable simply by adding an attribute to the sub definition? (Don't remember which one it was, though.)

echo , 2014-10-11 18:23:01

https://metacpan.org/pod/Exporter::Auto

Exporter::Auto. this is all you need.

Tero Niemi , 2013-04-02 00:32:25

Although it is not usually wise to dump all sub s from module into the caller namespace, it is sometimes useful (and more DRY!) to automatically generate @EXPORT_OK and %EXPORT_TAGS variables.

The easiest method is to extend the Exporter. A simple example is something like this:

package Exporter::AutoOkay;
#
#   Automatically add all subroutines from caller package into the
#   @EXPORT_OK array. In the package use like Exporter, f.ex.:
#
#       use parent 'Exporter::AutoOkay';
#
use warnings;
use strict;
no strict 'refs';

require Exporter;

sub import {
    my $package = $_[0].'::';

    # Get the list of exportable items
    my @export_ok = (@{$package.'EXPORT_OK'});

    # Automatically add all subroutines from package into the list
    foreach (keys %{$package}) {
        next unless defined &{$package.$_};
        push @export_ok, $_;
    }

    # Set variable ready for Exporter
    @{$package.'EXPORT_OK'} = @export_ok;

    # Let Exporter do the rest
    goto &Exporter::import;
}

1;

Note the use of goto that removes us from the caller stack.

A more complete example can be found here: http://pastebin.com/Z1QWzcpZ It automatically generates tag groups from subroutine prefixes.

Sérgio , 2013-11-14 21:38:06

case 1

Library is :

package mycommon;

use strict;
use warnings;

sub onefunctionthatyoumadeonlibary() {
}
1;

you can use it, calling common:: :

#!/usr/bin/perl
use strict;
use warnings;
use mycommon;

common::onefunctionthatyoumadeonlibary()
case 2

Library is , yousimple export them :

package mycommon;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT = qw(onefunctionthatyoumadeonlibary);
sub onefunctionthatyoumadeonlibary() {
}
1;

use it in same "namespace":

#!/usr/bin/perl
use strict;
use warnings;
use mycommon qw(onefunctionthatyoumadeonlibary);

onefunctionthatyoumadeonlibary()

Also we can do a mix of this two cases , we can export more common functions to use it without calling the packages name and other functions that we only call it with package name and that ones don't need to be exported.

> ,

You will have to do some typeglob munging. I describe something similar here:

Is there a way to "use" a single file that in turn uses multiple others in Perl?

The import routine there should do exactly what you want -- just don't import any symbols into your own namespace.

[Nov 29, 2019] Was Mikhail Gorbachev an incompetent leader or a stooge of the West - Quora

Nov 29, 2019 | www.quora.com

Joe Venetos , history, European Union and politics, int'l relations Answered Aug 22 2017 · Author has 485 answers and 325k answer views

Neither.

The USSR as it was was not sustainable, and the writing was all over the wall.

The reason it wasn't sustainable, however, is widely misunderstood.

The Soviet Union could have switched to a market or hybrid economy and still remained a unified state. However, it was made up of 15 very different essentially nation-states from Estonia to Uzbekistan, and separatist movements were tearing the Union apart.

Unlike other multi-national European empires that met their day earlier in the 20th century, such as the British, French, Portuguese, Austro-Hungarian, or Ottoman Empires, the Russian Empi...

(more) Loading

Neither.

The USSR as it was was not sustainable, and the writing was all over the wall.

The reason it wasn't sustainable, however, is widely misunderstood.

The Soviet Union could have switched to a market or hybrid economy and still remained a unified state. However, it was made up of 15 very different essentially nation-states from Estonia to Uzbekistan, and separatist movements were tearing the Union apart.

Unlike other multi-national European empires that met their day earlier in the 20th century, such as the British, French, Portuguese, Austro-Hungarian, or Ottoman Empires, the Russian Empire never had the chance to disband; the can was simply kicked down the road by the Bolshevik revolution and the Soviet era. Restrictions on free speech and press, followed by a gradual economic downturn that began in the 1970s, brewed anti-Union and separatist sentiments among sizeable sections of society. It's important to note, however, that not everyone wanted the disband the USSR, and not everyone in the Russian republic wanted to keep it together (the Central Asian states were the most reluctant to secede). There was, actually, a referendum on whether or not to keep the Union together, and a slight majority voted in favor (something Gorbachev points out to this day), but the vote was also boycotted by quite a few people, especially in the Baltic republics. So, we know that the citizens had mixed feelings and the reasons for the USSR's end were far more complex than just "communism failed".

By the summer of 1991, there was nothing Gorbachev could do. The hardliners saw him as incompetent to save the Union, but too many citizens and military personnel had defected to the politicians of the constituent republics (rather than the Union's leadership), including Russia itself, that were increasingly pursuing their independence since the first multiparty elections across the Union in 1989. By December 1991, Union-level political bodies agreed to disband. So, Gorbachev had no choice but to admit that the USSR no longer existed.

Gorbachev could have ruled with an iron fist, and he could have done so from the 1985 without ever implementing glasnost and perestroika, but that could have been a disaster. We don't really know, actually, but in my opinion, an oligarchy -which is what the USSR was in its later years, not an authoritarian state like it was under Stalin- still needs some level of public consent to continue governing, like China (which is also a diverse society, but far more homogenous than the USSR was). If you have all this economic and separatist malaise brewing, it's not going to work out.

In the long run, Russia is much better off. They now have a state where ethnic Russians make up 80% of the population (a good balance), from what was, I think 50% in the USSR.

While some Russians regret that the USSR ended, others don't care or were ready to call themselves "Russian" rather than "Soviet". It's no different to French public opinion turning against the Algerian war in the 1960s and supporting Algerian independence, or British public opinion starting to support the independence of India yet some people from those countries, may look back fondly. Also, Russia went through a tough economic period in the 1990s, which strengthened Soviet nostalgia, understandably, thinking back to a time when the state guaranteed everyone with housing and a job. While some sentiments still exist today in the Russian Federation that may appear pro-Soviet, it's important to point out that that doesn't necessarily mean these folks would like to recreate the Soviet Union as it was . Many just simply miss the heaftier influence the USSR had, versus what they perceive to be weakness or disrespect for Russia today. The communist party today gets few votes in Russian elections; and many Russians now were not adults prior to 1991, and thus don't quite remember the era too well; many others may be old enough to remember the economic downturn of the 80s, and not the economic good times of the 60s.

One final point, regarding Gorbachev being a "stooge of the West": that gives far too much credit to America under Reagan for taking down the USSR. The "West" had nothing to do with it. In the longer run, as we may be seeing slowly unravel since the Bush Jr administration, America pretty much screwed itself with the massive military spending that started in the 80s and continues upward, with supporting the mujahedeen to lure the USSR into Afghanistan in 1979 (a war that lasted until 1989), with opposing any secular regime in the Middle East friendly to Moscow in the 70s and 80s, and so on we all know how these events started playing out for the US much later, from 9/11 to the current Trump mess.

[Nov 23, 2019] Static local variables in Perl

Jan 01, 2012 | stackoverflow.com

Ask Question Asked 7 years, 5 months ago Active 2 years, 8 months ago Viewed 12k times


Charles , 2012-05-31 20:50:19

I'm looking for advice on Perl best practices. I wrote a script which had a complicated regular expression:
my $regex = qr/complicated/;

# ...

sub foo {
  # ...

  if (/$regex/)
  # ...
}

where foo is a function which is called often, and $regex is not used outside that function. What is the best way to handle situations like this? I only want it to be interpreted once, since it's long and complicated. But it seems a bit questionable to have it in global scope since it's only used in that sub. Is there a reasonable way to declare it static?

A similar issue arises with another possibly-unjustified global. It reads in the current date and time and formats it appropriately. This is also used many times, and again only in one function. But in this case it's even more important that it not be re-initialized, since I want all instances of the date-time to be the same from a given invocation of the script, even if the minutes roll over during execution.

At the moment I have something like

my ($regex, $DT);

sub driver {
  $regex = qr/complicated/;
  $DT = dateTime();
  # ...
}

# ...

driver();

which at least slightly segregates it. But perhaps there are better ways.

Again: I'm looking for the right way to do this, in terms of following best practices and Perl idioms. Performance is nice but readability and other needs take priority if I can't have everything.

hobbs ,

If you're using perl 5.10+, use a state variable.
use feature 'state';
# use 5.010; also works

sub womble {
    state $foo = something_expensive();
    return $foo ** 2;
}

will only call something_expensive once.

If you need to work with older perls, then use a lexical variable in an outer scope with an extra pair of braces:

{
    my $foo = something_expensive();
    sub womble {
        return $foo ** 2;
    }
}

this keeps $foo from leaking to anyone except for womble .

ikegami , 2012-05-31 21:14:04

Is there any interpolation in the pattern? If not, the pattern will only be compiled once no matter how many times the qr// is executed.
$ perl -Mre=debug -e'qr/foo/ for 1..10' 2>&1 | grep Compiling | wc -l
1

$ perl -Mre=debug -e'qr/foo$_/ for 1..10' 2>&1 | grep Compiling | wc -l
10

Even if there is interpolation, the pattern will only be compiled if the interpolated variables have changed.

$ perl -Mre=debug -e'$x=123; qr/foo$x/ for 1..10;' 2>&1 | grep Compiling | wc -l
1

$ perl -Mre=debug -e'qr/foo$_/ for 1..10' 2>&1 | grep Compiling | wc -l
10

Otherwise, you can use

{
   my $re = qr/.../;
   sub foo {
      ...
      /$re/
      ...
   }
}

or

use feature qw( state );
sub foo {
   state $re = qr/.../;
   ...
   /$re/
   ...
}

Alan Rocker , 2014-07-02 16:25:27

Regexes can be specified with the "o" modifier, which says "compile pattern once only" - in the 3rd. edition of the Camel, see p. 147

zoul ,

There's a state keyword that might be a good fit for this situation:
sub foo {
    state $regex = /.../;
    ...
}

TrueY , 2015-01-23 10:14:12

I would like to complete ikegami 's great answer. Some more words I would like to waste on the definition of local variables in pre 5.10 perl .

Let's see a simple example code:

#!/bin/env perl 

use strict;
use warnings;

{ # local 
my $local = "After Crying";
sub show { print $local,"\n"; }
} # local

sub show2;

show;
show2;

exit;

{ # local 
my $local = "Solaris";
sub show2 { print $local,"\n"; }
} # local

The user would expect that both sub will print the local variable, but this is not true!

Output:

After Crying
Use of uninitialized value $local in print at ./x.pl line 20.

The reason is that show2 is parsed, but the initialization of the local variable is not executed! (Of course if exit is removed and a show2 is added at the end, Solaris will be printed in the thirds line)

This can be fixed easily:

{ # local 
my $local;
BEGIN { $local = "Solaris"; }
sub show2 { print $local,"\n"; }
} # local

And now the output what was expected:

After Crying
Solaris

But state in 5.10+ is a better choice...

I hope this helps!

[Nov 23, 2019] Introduction to Perl Modules

Nov 23, 2019 | ods.com.ua

CONTENTS


This chapter introduces you to the concepts behind references to Perl modules, packages, and classes. It also shows you how to create a few sample modules.

What Is a Perl Module?

A Perl module is a set of Perl code that acts like a library of function calls. The term module in Perl is synonymous with the word package . Packages are a feature of Perl 4, whereas modules are prevalent in Perl 5.

You can keep all your reusable Perl code specific to a set of tasks in a Perl module. Therefore, all the functionality pertaining to one type of task is contained in one file. It's easier to build an application on these modular blocks. Hence, the word module applies a bit more than package .

Here's a quick introduction to modules. Certain topics in this section will be covered in detail throughout the rest of the book. Read the following paragraphs carefully to get an overview of what lies ahead as you write and use your own modules.

What is confusing is that the terms module and package are used interchangeably in all Perl documentation, and these two terms mean the very same thing . So when reading Perl documents, just think "package" when you see "module" and vice versa.

So, what's the premise for using modules? Well, modules are there to package (pardon the pun) variables, symbols, and interconnected data items together. For example, using global variables with very common names such as $k , $j , or $i in a program is generally not a good idea. Also, a loop counter, $i , should be allowed to work independently in two different portions of the code. Declaring $i as a global variable and then incrementing it from within a subroutine will create unmanageable problems with your application code because the subroutine may have been called from within a loop that also uses a variable called $i . The use of modules in Perl allows variables with the same name to be created at different, distinct places in the same program.

The symbols defined for your variables are stored in an associative array, referred to as a symbol table . These symbol tables are unique to a package. Therefore, variables of the same name in two different packages can have different values.

Each module has its own symbol table of all symbols that are declared within it. The symbol table basically isolates synonymous names in one module from another. The symbol table defines a namespace , that is, a space for independent variable names to exist in. Thus, the use of modules, each with its own symbol table, prevents a variable declared in one section from overwriting the values of other variables with the same name declared elsewhere in the same program.

As a matter of fact, all variables in Perl belong to a package. The variables in a Perl program belong to the main package. All other packages within a Perl program either are nested within this main package or exist at the same level. There are some truly global variables, such as the signal handler array %SIG , that are available to all other modules in an application program and cannot be isolated via namespaces. Only those variable identifiers starting with letters or an underscore are kept in a module's symbol table. All other symbols, such as the names STDIN , STDOUT , STDERR , ARGV , ARGVOUT , ENV , Inc , and SIG are forced to be in package _main.

Switching between packages affects only namespaces. All you are doing when you use one package or another is declaring which symbol table to use as the default symbol table for lookup of variable names. Only dynamic variables are affected by the use of symbol tables. Variables declared by the use of the my keyword are still resolved with the code block they happen to reside in and are not referenced through symbol tables. In fact, the scope of a package declaration remains active only within the code block it is declared in. Therefore, if you switch symbol tables by using a package within a subroutine, the original symbol table in effect when the call was made will be restored when the subroutine returns.

Switching symbol tables affects only the default lookup of dynamic variable names. You can still explicitly refer to variables, file handles, and so on in a specific package by prepending a packageName :: to the variable name. You saw what a package context was when using references in Chapter 3 . A package context simply implies the use of the symbol table by the Perl interpreter for resolving variable names in a program. By switching symbol tables, you are switching the package context.

Modules can be nested within other modules. The nested module can use the variables and functions of the module it is nested within. For nested modules, you would have to use moduleName :: nestedModuleName and so on. Using the double colon ( :: ) is synonymous with using a back quote ( ` ). However, the double colon is the preferred, future way of addressing variables within modules.

Explicit addressing of module variables is always done with a complete reference. For example, suppose you have a module, Investment , which is the default package in use, and you want to address another module, Bonds , which is nested within the Investment module. In this case, you cannot use Bond:: . Instead, you would have to use Investment::Bond:: to address variables and functions within the Bond module. Using Bond:: would imply the use of a package Bond that is nested within the main module and not within the Investment module.

The symbol table for a module is actually stored in an associative array of the module's names appended with two colons. The symbol table for a module called Bond will be referred to as the associative array %Bond:: . The name for the symbol table for the main module is %main:: , and can even be shortened to %:: . Similarly, all nested packages have their symbols stored in associative arrays with double colons separating each nesting level. For example, in the Bond module that is nested within the Investment module, the associative array for the symbols in the Bond module will be named %Investment::Bond:: .

A typeglob is really a global type for a symbol name. You can perform aliasing operations by assigning to a typeglob . One or more entries in an associative array for symbols will be used when an assignment via a typeglob is used. The actual value in each entry of the associative array is what you are referring to when you use the * variableName notation. Thus, there are two ways of referring to variable names in a package:

*Investment::money = *Investment::bills;

$Investment::{'money'} = $Investment::{'bills'};

In the first method, you are referring to the variables via a typeglob reference. The use of the symbol table, %Investment:: , is implied here, and Perl will optimize the lookup for symbols money and bills . This is the faster and preferred way of addressing a symbol. The second method uses a lookup for the value of a variable addressed by 'money' and 'bills' in the associative array used for symbols, %Investment:: explicitly. This lookup would be done dynamically and will not be optimized by Perl. Therefore, the lookup will be forced to check the associative array every time the statement is executed. As a result, the second method is not efficient and should be used only for demonstration of how the symbol table is implemented internally.

Another example in this statement

*kamran = *husain;

causes variables, subroutines, and file handles that are named via the symbol kamran to also be addressed via the symbol husain . That is, all symbol entries in the current symbol table with the key kamran will now contain references to those symbols addressed by the key husain . To prevent such a global assignment, you can use explicit references. For example, the following statement will let you address the contents of $husain via the variable $kamran :

*kamran = \$husain;

However, any arrays such @kamran and @husain will not be the same. Only what the references specified explicitly will be changed. To summarize, when you assign one typeglob to another, you affect all the entries in a symbol table regardless of the type of variable being referred to. When you assign a reference from one variable type to another, you are only affecting one entry in the symbol table.

A Perl module file has the following format:

package ModuleName;
...
#### Insert module code ####
...
1;

The filename has to be called ModuleName.pm . The name of a module must end in the string .pm by convention. The package statement is the first line of the file. The last line of the file must contain the line with the 1; statement. This in effect returns a true value to the application program using the module. Not using the 1; statement will not let the module be loaded correctly.

The package statement tells the Perl interpreter to start with a new namespace domain. Basically, all your variables in a Perl script belong to a package called main . Every variable in the main package can be referred to as $main'variable .

Here's the syntax for such references:

$packageName'variableName

The single quote ( ' ) is synonymous with the double colon ( :: ) operator. I cover more uses of the :: operator in the next chapter. For the time being, you must remember that the following two statements are equivalent:

$packageName'variableName;
$packageName::variableName;

The double-colon syntax is considered standard in the Perl world. Therefore, to preserve readability, I use the double-colon syntax in the rest of this book unless it's absolutely necessary to make exceptions to prove a point.

The default use of a variable name defers to the current package active at the time of compilation. Thus, if you are in the package Finance.pm and specify a variable $pv , the variable is actually equal to $Finance::$pv .

Using Perl Modules: use vs. require

You include Perl modules in your program by using the use or the require statement. Here's the way to use either of these statements:

use ModuleName;
require ModuleName;

Note that the .pm extension is not used in the code shown above. Also note that neither statement allows a file to be included more than once in a program. The returned value of true ( 1; ) as the last statement is required to let Perl know that a require d or use d module loaded correctly and lets the Perl interpreter ignore any reloads. In general, it's better to use the use Module; statement than the require Module; statement in a Perl program to remain compatible with future versions of Perl.

For modules, you might want to consider continuing to use the require statement. Here's why: The use statement does a little bit more work than the require statement in that it alters the namespace of the module that includes another module. You want this extra update of the namespace to be done in a program. However, when writing code for a module, you may not want the namespace to be altered unless it's explicitly required. In this event, you will use the require statement.

The require statement includes the full pathname of a file in the @Inc array so that the functions and variables in the module's file are in a known location during execution time. Therefore, the functions that are imported from a module are imported via an explicit module reference at runtime with the require statement. The use statement does the same thing as the require statement because it updates the @Inc array with full pathnames of loaded modules. The code for the use function also goes a step further and calls an import function in the module being use d to explicitly load the list of exported functions at compile time, thus saving the time required for an explicit resolution of a function name during execution.

Basically, the use statement is equivalent to

require ModuleName; import ModuleName [list of imported functions];

The use of the use statement does change your program's namespace because the imported function names are inserted in the symbol table. The require statement does not alter your program's namespace. Therefore, the following statement

use ModuleName ();

is equivalent to this statement:

require ModuleName;

Functions are imported from a module via a call to a function called import . You can write your own import function in a module, or you can use the Exporter module and use its import function. In almost all cases, you will use the Exporter module to provide an import function instead of reinventing the wheel. (You'll learn more on this in the next section.) Should you decide not to use the Exporter module, you will have to write your own import function in each module that you write. It's much easier to simply use the Exporter module and let Perl do the work for you.

The Sample Letter.pm Module

The best way to illustrate the semantics of how a module is used in Perl is to write a simple module and show how to use it. Let's take the example of a local loan shark, Rudious Maximus, who is simply tired of typing the same "request for payment" letters. Being an avid fan of computers and Perl, Rudious takes the lazy programmer's approach and writes a Perl module to help him generate his memos and letters.

Now, instead of typing within fields in a memo template file, all he has to do is type a few lines to produce his nice, threatening note. Listing 4.1 shows you what he has to type.


Listing 4.1. Using the Letter module.
1 #!/usr/bin/perl -w
2 #
3 # Uncomment the line below to include the current dir in @Inc.
4 # push (@Inc, 'pwd');
5 #
6 use Letter;
7
8 Letter::To("Mr. Gambling Man","The money for Lucky Dog, Race 2");
9 Letter::ClaimMoneyNice();
10 Letter::ThankDem();
11 Letter::Finish();

The use Letter; statement is present to force the Perl interpreter to include the code for the module in the application program. The module should be located in the /usr/lib/perl5/ directory, or you can place it in any directory listed in the @Inc array. The @Inc array is the list of directories that the Perl interpreter will look for when attempting to load the code for the named module. The commented line (number 4) shows how to add the current working directory to include the path. The next four lines in the file generate the subject matter for the letter.

Here's the output from using the Letter module:

To: Mr. Gambling Man
Fm: Rudious Maximus, Loan Shark
Dt: Wed Feb 7 10:35:51 CST 1996

Re: The money for Lucky Dog, Race 2

====================================================

It has come to my attention that your account is
way over due.
You gonna pay us soon?
Or would you like me to come ovah?

Thanks for your support.

Sincerely,
Rudious

The Letter module file is shown in Listing 4.2. The name of the package is declared in the first line. Because this module's functions will be exported, I use the Exporter module. Therefore, the statement use Exporter; is required to inherit functionality from the Exporter module. Another required step is putting the word Exported in the @ISA array to allow searching for Exported.pm .

Note
The @ISA array is a special array within each package. Each item in the array lists where else to look for a method if it cannot be found in the current package. The order in which packages are listed in the @ISA array is the order in which Perl searches for unresolved symbols. A class that is listed in the @ISA array is referred to as the base class of that particular class. Perl will cache missing methods found in base classes for future references. Modifying the @ISA array will flush the cache and cause Perl to look up all methods again.

Let's now look at the code for Letter.pm in Listing 4.2.


Listing 4.2. The Letter.pm module.
1 package Letter;
2
3 require Exporter;
4 @ISA = (Exporter);
5
6 =head1 NAME
7
8 Letter - Sample module to generate letterhead for you
9
10 =head1 SYNOPSIS
11
12 use Letter;
13
14 Letter::Date();
15 Letter::To($name,$company,$address);
16
17 Then one of the following:
18 Letter::ClaimMoneyNice() {
19 Letter::ClaimMoney();
20 Letter::ThreatBreakLeg();
21
22 Letter::ThankDem();
23 Letter::Finish();
24
25 =head1 DESCRIPTION
26
27 This module provides a short example of generating a letter for a
28 friendly neighborbood loan shark.
29
30 The code begins after the "cut" statement.
31 =cut
32
33 @EXPORT = qw( Date,
34 To,
35 ClaimMoney,
36 ClaimMoneyNice,
37 ThankDem,
38 Finish );
39
40 #
41 # Print today's date
42 #
43 sub Letter::Date {
44 $date = 'date';
45 print "\n Today is $date";
46 }
47
48 sub Letter::To {
49 local($name) = shift;
50 local($subject) = shift;
51 print "\n To: $name";
52 print "\n Fm: Rudious Maximus, Loan Shark";
53 print "\n Dt: ", `date`;
54 print "\n Re: $subject";
55 print "\n\n";
56 print "\n====================================================\n";
57 }
58 sub Letter::ClaimMoney() {
59 print "\n You owe me money. Get your act together";
60 print "\n Do you want me to send Bruno over to ";
61 print "\n collect it , or are you gonna pay up?";
62 }
63
64 sub Letter::ClaimMoneyNice() {
65 print "\n It is come to my attention that your account is ";
66 print "\n way over due.";
67 print "\n You gonna pay us soon..";
68 print "\n or would you like me to come ovah?";
69 }
70
71 sub Letter::ThreatBreakLeg() {
72 print "\n apparently letters like these dont help";
73 print "\n I will have to make an example of you";
74 print "\n \n See you in the hospital, pal!";
75 }
76
77 sub Letter::ThankDem() {
78 print "\n\n Thanks for your support";
79 }
80
81 sub Letter::Finish(){
82 printf "\n\n\n\n Sincerely";
83 printf "\n Rudious \n ";
84 }
85
86 1;

Lines containing the equal sign are used for documentation. You must document each module for your own reference; Perl modules do not need to be documented, but it's a good idea to write a few lines about what your code does. A few years from now, you may forget what a module is about. Good documentation is always a must if you want to remember what you did in the past!

I cover documentation styles used for Perl in Chapter 8 , "Documenting Perl Scripts." For this sample module, the =head1 statement begins the documentation. Everything up to the =cut statement is ignored by the Perl interpreter.

Next, the module lists all the functions exported by this module in the @EXPORT array. The @EXPORT array defines all the function names that can be called by outside code. If you do not list a function in this @EXPORT array, it won't be seen by external code modules.

Following the @EXPORT array is the body of the code, one subroutine at a time. After all the subroutines are defined, the final statement 1; ends the module file. 1; must be the last executable line in the file.

Let's look at some of the functions defined in this module. The first function to look at is the simple Date function, lines 43 to 46, which prints the current UNIX date and time. There are no parameters to this function, and it doesn't return anything meaningful back to the caller.

Note the use of my before the $date variable in line 44. The my keyword is used to limit the scope of the variable to within the Date function's curly braces. Code between curly braces is referred to as a block . Variables declared within a block are limited in scope to within the curly braces. In 49 and 50, the local variables $name and $subject are visible to all functions.

You can also declare variables with the local qualifier. The use of local allows a variable to be in scope for the current block as well as for other blocks of code called from within this block. Thus, a local $x declared within one block is visible to all subsequent blocks called from within this block and can be referenced. In the following sample code, the ToTitled function's $name variable can be accessed but not the data in $iphone :

1 sub Letter::ToTitled {
2 local($name) = shift;
3 my($phone) = shift;
Subroutines and Passing Parameters

The sample code for Letter.pm showed how to extract one parameter at a time. The subroutine To() takes two parameters to set up the header for the memo.

Using functions within a module is not any different than using and defining Perl modules within the same code file. Parameters are passed by reference unless otherwise specified. Multiple arrays passed into a subroutine, if not explicitly dereferenced using the backslash, are concatenated.

The @_ input array in a function is always an array of scalar values. Passing values by reference is the preferred way in Perl to pass a large amount of data into a subroutine. ( See Chapter 3 , "References.")

Another Sample Module: Finance

The Finance module, shown in Listing 4.3, is used to provide simple calculations for loan values. Using the Finance module is straightforward. All the functions are written with the same parameters, as shown in the formula for the functions.

Let's look at how the future value of an investment can be calculated. For example, if you invest some dollars, $pv , in a bond that offers a fixed percentage rate, $r , applied at known intervals for $n time periods, what is the value of the bond at the time of its expiration? In this case, you'll be using the following formula:

$fv = $pv * (1+$r) ** $n ;

The function to get the future value is declared as FutureValue . Refer to Listing 4.3 to see how to use it.


Listing 4.3. Using the Finance module.
1 #!/usr/bin/perl -w
2
3 push(@Inc,'pwd');
4 use Finance;
5
6 $loan = 5000.00;
7 $apr = 3.5; # APR
8 $year = 10; # in years.
9
10 # ----------------------------------------------------------------
11 # Calculate the value at the end of the loan if interest
12 # is applied every year.
13 # ----------------------------------------------------------------
14 $time = $year;
15 $fv1 = Finance::FutureValue($loan,$apr,$time);
16 print "\n If interest is applied at end of year";
17 print "\n The future value for a loan of \$" . $loan . "\n";
18 print " at an APR of ", $apr , " for ", $time, " years";
19 printf " is %8.2f \n" , $fv1;
20
21 # ----------------------------------------------------------------
22 # Calculate the value at the end of the loan if interest
23 # is applied every month.
24 # ----------------------------------------------------------------
25 $rate = $apr / 12; # APR
26 $time = $year * 12; # in months
27 $fv2 = Finance::FutureValue($loan,$rate,$time);
28
29 print "\n If interest is applied at end of each month";
30 print "\n The future value for a loan of \$" . $loan . "\n";
31 print " at an APR of ", $apr , " for ", $time, " months";
32 printf " is %8.2f \n" , $fv2;
33
34 printf "\n The difference in value is %8.2f", $fv2 - $fv1;
35 printf "\n Therefore by applying interest at shorter time periods";
36 printf "\n we are actually getting more money in interest.\n";

Here is sample input and output of Listing 4.3.

$ testme

If interest is applied at end of year
The future value for a loan of $5000
at an APR of 3.5 for 10 years is 7052.99

If interest is applied at end of each month
The future value for a loan of $5000
at an APR of 3.5 for 120 months is 7091.72

The difference in value is 38.73
Therefore by applying interest at shorter time periods
we are actually getting more money in interest.

The revelation in the output is the result of the comparison of values between $fv1 and $fv2 . The $fv1 value is calculated with the application of interest once every year over the life of the bond. $fv2 is the value if the interest is applied every month at the equivalent monthly interest rate.

The Finance.pm package is shown in Listing 4.4 in its early development stages.


Listing 4.4. The Finance.pm package.
1 package Finance;
2
3 require Exporter;
4 @ISA = (Exporter);
5
6 =head1 Finance.pm
7
8 Financial Calculator - Financial calculations made easy with Perl
9
10 =head 2
11 use Finance;
12
13 $pv = 10000.0;
14
15 $rate = 12.5 / 12; # APR per month.
16
17 $time = 360 ; # months for loan to mature
18
19 $fv = FutureValue();
20
21 print $fv;
22
23 =cut
24
25 @EXPORT = qw( FutureValue,
26 PresentValue,
27 FVofAnnuity,
28 AnnuityOfFV,
29 getLastAverage,
30 getMovingAverage,
31 SetInterest);
32
33 #
34 # Globals, if any
35 #
36
37 local $defaultInterest = 5.0;
38
39 sub Finance::SetInterest($) {
40 my $rate = shift(@_);
41 $defaultInterest = $rate;
42 printf "\n \$defaultInterest = $rate";
43 }
44
45 # --------------------------------------------------------------------
46 # Notes:
47 # 1. The interest rate $r is given in a value of [0-100].
48 # 2. The $n given in the terms is the rate at which the interest
49 # is applied.
50 #
51 # --------------------------------------------------------------------
52
53 # --------------------------------------------------------------------
54 # Present value of an investment given
55 # fv - a future value
56 # r - rate per period
57 # n - number of period
58 # --------------------------------------------------------------------
59 sub Finance::FutureValue($$$) {
60 my ($pv,$r,$n) = @_;
61 my $fv = $pv * ((1 + ($r/100)) ** $n);
62 return $fv;
63 }
64
65 # --------------------------------------------------------------------
66 # Present value of an investment given
67 # fv - a future value
68 # r - rate per period
69 # n - number of period
70 # --------------------------------------------------------------------
71 sub Finance::PresentValue($$$) {
72 my $pv;
73 my ($fv,$r,$n) = @_;
74 $pv = $fv / ((1 + ($r/100)) ** $n);
75 return $pv;
76
77 }
78
79 # --------------------------------------------------------------------
80 # Get the future value of an annuity given
81 # mp - Monthly Payment of Annuity
82 # r - rate per period
83 # n - number of period
84 # --------------------------------------------------------------------
85
86 sub FVofAnnuity($$$) {
87 my $fv;
88 my $oneR;
89 my ($mp,$r,$n) = @_;
90
91 $oneR = ( 1 + $r) ** $n;
92 $fv = $mp * ( ($oneR - 1)/ $r);
93 return $fv;
94 }
95
96 # --------------------------------------------------------------------
97 # Get the annuity from the following bits of information
98 # r - rate per period
99 # n - number of period
100 # fv - Future Value
101 # --------------------------------------------------------------------
102
103 sub AnnuityOfFV($$$) {
104 my $mp; # mp - Monthly Payment of Annuity
105 my $oneR;
106 my ($fv,$r,$n) = @_;
107
108 $oneR = ( 1 + $r) ** $n;
109 $mp = $fv * ( $r/ ($oneR - 1));
110 return $mp;
111 }
112
113 # --------------------------------------------------------------------
114 # Get the average of the last "n" values in an array.
115 # --------------------------------------------------------------------
116 # The last $count number of elements from the array in @values
117 # The total number of elements in @values is in $number
118 #
119 sub getLastAverage($$@) {
120 my ($count, $number, @values) = @_;
121 my $i;
122
123 my $a = 0;
124 return 0 if ($count == 0);
125 for ($i = 0; $i< $count; $i++) {
126 $a += $values[$number - $i - 1];
127 }
128 return $a / $count;
129 }
130
131 # --------------------------------------------------------------------
132 # Get a moving average of the values.
133 # --------------------------------------------------------------------
134 # The window size is the first parameter, the number of items in the
135 # passed array is next. (This can easily be calculated within the
136 # function using the scalar() function, but the subroutine shown here
137 # is also being used to illustrate how to pass pointers.) The reference to the
138 # array of values is passed next, followed by a reference to the place
139 # the return values are to be stored.
140 #
141 sub getMovingAve($$\@\@) {
142 my ($count, $number, $values, $movingAve) = @_;
143 my $i;
144 my $a = 0;
145 my $v = 0;
146
147 return 0 if ($count == 0);
148 return -1 if ($count > $number);
149 return -2 if ($count < 2);
150
151 $$movingAve[0] = 0;
152 $$movingAve[$number - 1] = 0;
153 for ($i=0; $i<$count;$i++) {
154 $v = $$values[$i];
155 $a += $v / $count;
156 $$movingAve[$i] = 0;
157 }
158 for ($i=$count; $i<$number;$i++) {
159 $v = $$values[$i];
160 $a += $v / $count;
161 $v = $$values[$i - $count - 1];
162 $a -= $v / $count;
163 $$movingAve[$i] = $a;
164 }
165 return 0;
166 }
167
168 1;

Look at the declaration of the function FutureValue with ($$$) . The three dollar signs together signify three scalar numbers being passed into the function. This extra scoping is present for validating the type of the parameters passed into the function. If you were to pass a string instead of a number into the function, you would get a message very similar to this one:

Too many arguments for Finance::FutureValue at ./f4.pl line 15, near "$time)"
Execution of ./f4.pl aborted due to compilation errors.

The use of prototypes when defining functions prevents you from sending in values other than what the function expects. Use @ or % to pass in an array of values. If you are passing by reference, use \@ or \% to show a scalar reference to an array or hash, respectively. If you do not use the backslash, all other types in the argument list prototype are ignored. Other types of disqualifiers include an ampersand for a reference to a function, an asterisk for any type, and a semicolon to indicate that all other parameters are optional.

Now, let's look at the lastMovingAverage function declaration, which specifies two integers in the front followed by an array. The way the arguments are used in the function is to assign a value to each of the two scalars, $count and $number , whereas everything else is sent to the array. Look at the function getMovingAverage() to see how two arrays are passed in order to get the moving average on a list of values.

The way to call the getMovingAverage function is shown in Listing 4.5.


Listing 4.5. Using the moving average function.
1 #!/usr/bin/perl -w
2
3 push(@Inc,'pwd');
4 use Finance;
5
6 @values = ( 12,22,23,24,21,23,24,23,23,21,29,27,26,28 );
7 @mv = (0);
8 $size = scalar(@values);
9 print "\n Values to work with = { @values } \n";
10 print " Number of values = $size \n";
11
12 # ----------------------------------------------------------------
13 # Calculate the average of the above function
14 # ----------------------------------------------------------------
15 $ave = Finance::getLastAverage(5,$size,@values);
16 print "\n Average of last 5 days = $ave \n";
17
18 Finance::getMovingAve(5,$size,@values,@mv);
19 print "\n Moving Average with 5 days window = \n { @mv } \n";

Here's the output from Listing 4.5:

Values to work with = { 12 22 23 24 21 23 24 23 23 21 29 27 26 28 }
Number of values = 14

Average of last 5 days = 26.2

Moving Average with 5 days window =
{ 0 0 0 0 0 19.4 21.8 22 22 21.4 23 23.8 24.2 25.2 }

The getMovingAverage() function takes two scalars and then two references to arrays as scalars. Within the function, the two scalars to the arrays are dereferenced for use as numeric arrays. The returned set of values is inserted in the area passed in as the second reference. Had the input parameters not been specified with \@ for each referenced array, the $movingAve array reference would have been empty and would have caused errors at runtime. In other words, the following declaration is not correct:

sub getMovingAve($$@@)

The resulting spew of error messages from a bad function prototype is as follows:

Use of uninitialized value at Finance.pm line 128.
Use of uninitialized value at Finance.pm line 128.
Use of uninitialized value at Finance.pm line 128.
Use of uninitialized value at Finance.pm line 128.
Use of uninitialized value at Finance.pm line 128.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.
Use of uninitialized value at Finance.pm line 133.
Use of uninitialized value at Finance.pm line 135.

Values to work with = { 12 22 23 24 21 23 24 23 23 21 29 27 26 28 }
Number of values = 14

Average of last 5 days = 26.2

Moving Average with 5 days window =
{ 0 }

This is obviously not the correct output. Therefore, it's critical that you pass by reference when sending more than one array.

Global variables for use within the package can also be declared. Look at the following segment of code from the Finance.pm module to see what the default value of the Interest variable would be if nothing was specified in the input. (The current module requires the interest to be passed in, but you can change this.)

Here's a little snippet of code that can be added to the end of the program shown in Listing 4.5 to add the ability to set interest rates.

20 local $defaultInterest = 5.0;
21 sub Finance::SetInterest($) {
22 my $rate = shift(@_);
23 $rate *= -1 if ($rate < 0);
24 $defaultInterest = $rate;
25 printf "\n \$defaultInterest = $rate";
26 }

The local variable $defaultInterest is declared in line 20. The subroutine SetInterest to modify the rate is declared in lines 21 through 26. The $rate variable uses the values passed into the subroutine and simply assigns a positive value for it. You can always add more error checking if necessary.

To access the defaultInterest variable's value, you could define either a subroutine that returns the value or refer to the value directly with a call to the following in your application program:

$Finance::defaultInterest;
Returned Values from Subroutines in a Package

The variable holding the return value from the module function is declared as my variable . The scope of this variable is within the curly braces of the function only. When the called subroutine returns, the reference to my variable is returned. If the calling program uses this returned reference somewhere, the link counter on the variable is not zero; therefore, the storage area containing the returned values is not freed to the memory pool. Thus, the function that declares

my $pv

and then later returns the value of $pv returns a reference to the value stored at that location. If the calling routine performs a call like this one:

Finance::FVofAnnuity($monthly,$rate,$time);

there is no variable specified here into which Perl stores the returned reference; therefore, any returned value (or a list of values) is destroyed. Instead, the call with the returned value assigned to a local variable, such as this one:

$fv = Finance::FVofAnnuity($monthly,$rate,$time);

maintains the variable with the value. Consider the example shown in Listing 4.6, which manipulates values returned by functions.


Listing 4.6. Sample usage of the my function.
1 #!/usr/bin/perl -w
2
3 push(@Inc,'pwd');
4 use Finance;
5
6 $monthly = 400;
7 $rate = 0.2; # i.e. 6 % APR
8 $time = 36; # in months
9
10 print "\n# ------------------------------------------------";
11 $fv = Finance::FVofAnnuity($monthly,$rate,$time);
12 printf "\n For a monthly %8.2f at a rate of %%%6.2f for %d periods",
13 $monthly, $rate, $time;
14 printf "\n you get a future value of %8.2f ", $fv;
15
16 $fv *= 1.1; # allow 10 % gain in the house value.
17
18 $mo = Finance::AnnuityOfFV($fv,$rate,$time);
19
20 printf "\n To get 10 percent more at the end, i.e. %8.2f",$fv;
21 printf "\n you need a monthly payment value of %8.2f",$mo,$fv;
22
23 print "\n# ------------------------------------------------ \n";

Here is sample input and output for this function:

$ testme
# ------------------------------------------------
For a monthly 400.00 at a rate of % 0.20 for 36 periods
you get a future value of 1415603.75
To get 10 percent more at the end, i.e. 1557164.12
you need a monthly payment value of 440.00
# ------------------------------------------------
Multiple Inheritance

Modules implement classes in a Perl program that uses the object-oriented features of Perl. Included in object-oriented features is the concept of inheritance . (You'll learn more on the object-oriented features of Perl in Chapter 5 , "Object-Oriented Programming in Perl .") Inheritance means the process with which a module inherits the functions from its base classes. A module that is nested within another module inherits its parent modules' functions. So inheritance in Perl is accomplished with the :: construct. Here's the basic syntax:

SuperClass::NextSubClass:: ... ::ThisClass.

The file for these is stored in ./SuperClass/NextSubClass/ . Each double colon indicates a lower-level directory in which to look for the module. Each module, in turn, declares itself as a package with statements like the following:

package SuperClass::NextSubClass;
package SuperClass::NextSubClass::EvenLower;

For example, say that you really want to create a Money class with two subclasses, Stocks and Finance . Here's how to structure the hierarchy, assuming you are in the /usr/lib/perl5 directory:

  1. Create a Money directory under the /usr/lib/perl5 directory.
  2. Copy the existing Finance.pm file into the Money subdirectory.
  3. Create the new Stocks.pm file in the Money subdirectory.
  4. Edit the Finance.pm file to use the line package Money::Finance instead of package Finance; .
  5. Edit scripts to use Money::Finance as the subroutine prefix instead of Finance:: .
  6. Create a Money.pm file in the /usr/lib/perl5 directory.

The Perl script that gets the moving average for a series of numbers is presented in Listing 4.7.


Listing 4.7. Using inheriting modules.
1 #!/usr/bin/perl -w
2 $aa = 'pwd';
3 $aa .= "/Money";
4 push(@Inc,$aa);
5 use Money::Finance;
6 @values = ( 12,22,23,24,21,23,24,23,23,21,29,27,26,28 );
7 @mv = (0);
8 $size = scalar(@values);
9 print "\n Values to work with = { @values } \n";
10 print " Number of values = $size \n";
11 # ----------------------------------------------------------------
12 # Calculate the average of the above function
13 # ----------------------------------------------------------------
14 $ave = Money::Finance::getLastAverage(5,$size,@values);
15 print "\n Average of last 5 days = $ave \n";
16 Money::Finance::getMovingAve(5,$size,@values,@mv);
17 # foreach $i (@values) {
18 # print "\n Moving with 5 days window = $mv[$i] \n";
19 # }
20 print "\n Moving Average with 5 days window = \n { @mv } \n";

Lines 2 through 4 add the path to the Money subdirectory. The use statement in line 5 now addresses the Finance.pm file in the ./Money subdirectory. The calls to the functions within Finance.pm are now called with the prefix Money::Finance:: instead of Finance:: . Therefore, a new subdirectory is shown via the :: symbol when Perl is searching for modules to load.

The Money.pm file is not required. Even so, you should create a template for future use. Actually, the file would be required to put any special requirements for initialization that the entire hierarchy of modules uses. The code for initialization is placed in the BEGIN() function. The sample Money.pm file is shown in Listing 4.8.


Listing 4.8. The superclass module for Finance.pm .
1 package Money;
2 require Exporter;
3
4 BEGIN {
5 printf "\n Hello! Zipping into existence for you\n";
6 }
7 1;

To see the line of output from the printf statement in line 5, you have to insert the following commands at the beginning of your Perl script:

use Money;
use Money::Finance;

To use the functions in the Stocks.pm module, you use this line:

use Money::Stocks;

The Stocks.pm file appears in the Money subdirectory and is defined in the same format as the Finance.pm file, with the exceptions that use Stocks is used instead of use Finance and the set of functions to export is different.

The Perl Module Libraries

A number of modules are included in the Perl distribution. Check the /usr/lib/perl5/lib directory for a complete listing after you install Perl. There are two kinds of modules you should know about and look for in your Perl 5 release, Pragmatic and Standard modules.

Pragmatic modules, which are also like pragmas in C compiler directives, tend to affect the compilation of your program. They are similar in operation to the preprocessor elements of a C program. Pragmas are locally scoped so that they can be turned off with the no command. Thus, the command

no POSIX ;

turns off the POSIX features in the script. These features can be turned back on with the use statement.

Standard modules bundled with the Perl package include several functioning packages of code for you to use. Refer to appendix B, "Perl Module Archives," for a complete list of these standard modules.

To find out all the .pm modules installed on your system, issue the following command. (If you get an error, add the /usr/lib/perl5 directory to your path.)

find /usr/lib/perl5 -name perl "*.pm" -print
Extension Modules

Extension modules are written in C (or a mixture of Perl and C) and are dynamically loaded into Perl if and when you need them. These types of modules for dynamic loading require support in the kernel. Solaris lets you use these modules. For a Linux machine, check the installation pages on how to upgrade to the ELF format binaries for your Linux kernel.

What Is CPAN?

The term CPAN (Comprehensive Perl Archive Network) refers to all the hosts containing copies of sets of data, documents, and Perl modules on the Net. To find out about the CPAN site nearest you, search on the keyword CPAN in search engines such as Yahoo!, AltaVista, or Magellan. A good place to start is the www.metronet.com site .

Summary

This chapter introduced you to Perl 5 modules and described what they have to offer. A more comprehensive list is found on the Internet via the addresses shown in the Web sites http://www.metronet.com and http://www.perl.com .

A Perl package is a set of Perl code that looks like a library file. A Perl module is a package that is defined in a library file of the same name. A module is designed to be reusable. You can do some type checking with Perl function prototypes to see whether parameters are being passed correctly. A module has to export its functions with the @EXPORT array and therefore requires the Exporter module. Modules are searched for in the directories listed in the @Inc array.

Obviously, there is a lot more to writing modules for Perl than what is shown in this chapter. The simple examples in this chapter show you how to get started with Perl modules. In the rest of the book I cover the modules and their features, so hang in there.

I cover Perl objects, classes, and related concepts in Chapter 5 .

[Nov 23, 2019] min, max, sum in Perl using ListUtil

See also ListMoreUtils - Provide the stuff missing in ListUtil - metacpan.org
Nov 23, 2019 | perlmaven.com
List::Util module provides a number of simple and some more complex functions that can be used on lists, anything that returns a list anything that can be seen as a list.

For example these can be used on arrays as they "return their content" in list context . min

If given a list of numbers to it, it will return the smallest number:

examples/min.pl

  1. use 5.010 ;
  2. use strict ;
  3. use warnings ;
  4. use List :: Util qw ( min );
  5. say min ( 10 , 3 , - 8 , 21 ); # -8
  6. my @prices = ( 17.2 , 23.6 , 5.50 , 74 , '10.3' );
  7. say min ( @prices ); # 5.5
  8. # Argument "2x" isn't numeric in subroutine entry at examples/min.pl line 14.
  9. say min ( 10 , 3 , '2x' , 21 ); # 2

If one of the arguments is a string that cannot be fully converted to a number automatically and if you have use warnings on as you should , then you'll see the following warnings: Argument ... isn't numeric in subroutine entry at ...

minstr

There is a corresponding function called minstr that will accept strings and sort them according to the ASCII order, though I guess it will work with Unicode as well if that's what you are feeding it.

examples/minstr.pl
  1. use 5.010 ;
  2. use strict ;
  3. use warnings ;
  4. use List :: Util qw ( minstr );
  5. say minstr ( 'f' , 'b' , 'e' ); # b

It can also accept numbers as parameters and will treat them as strings. The result might surprise you, if you are not familiar with the automatic number to string conversion of Perl, and that the string "11" is ahead of the string "2" because the comparison works character-by-character and in this case the first character of "11" is ahead of the first (and only) character of "2" in the ASCII table.

examples/minstr_numbers.pl

  1. use 5.010 ;
  2. use strict ;
  3. use warnings ;
  4. use List :: Util qw ( minstr );
  5. say minstr ( 2 , 11 , 99 ); # 11

After all internally it uses the lt operator.

max

Similar to min just returns the biggest number.

maxstr

Similar to minstr , returns the biggest string in ASCII order.

sum

The sum function adds up the provided numbers and returns their sum. If one or more of the values provided is a string that cannot be fully converted to a number it will generate a warning like this: Argument ... isn't numeric in subroutine entry at ... . If the parameters of sum are empty the function returns undef . This is unfortunate as it should be 0, but in order to provide backwards compatibility, if the provided list is empty then undef is returned.

examples/sum.pl

  1. use 5.010 ;
  2. use strict ;
  3. use warnings ;
  4. use List :: Util qw ( sum );
  5. say sum ( 10 , 3 , - 8 , 21 ); # 26
  6. my @prices = ( 17.2 , 23.6 , '1.1' );
  7. say sum ( @prices ); # 41.9
  8. my @empty ;
  9. # Use of uninitialized value in say at examples/sum.pl line 14.
  10. say sum ( @empty ); # (prints nothing)
sum0

In order to fix the above issue, that sum() return undef , in version 1.26 of the module, in 2012, a new function called sum0 was introduced that behaves exactly like the sum function, but returns 0 if no values was supplied.

examples/sum0.pl

  1. use 5.010 ;
  2. use strict ;
  3. use warnings ;
  4. use List :: Util qw ( sum0 );
  5. say sum0 ( 10 , 3 , - 8 , 21 ); # 26
  6. my @prices = ( 17.2 , 23.6 , '1.1' );
  7. say sum0 ( @prices ); # 41.9
  8. my @empty ;
  9. say sum0 ( @empty ); # 0
product

The product function multiplies its parameters. As this function is newer it was not constrained with backward compatibility issues so if the provided list is empty, the returned value will be 1.

examples/product.pl

  1. use 5.010 ;
  2. use strict ;
  3. use warnings ;
  4. use List :: Util qw ( product );
  5. my @interest = ( 1.2 , 2.6 , 4 , '1.3' );
  6. say product ( @interest ); # 16.224
  7. my @empty ;
  8. say product ( @empty ); # 1
Other functions of List::Util

The module has a number of other functions that were used in various other articles:

first

first returns the first element from a list that satisfies the given condition. For examples on how to use it an why is it good check out the articles Fast lookup by name or by date - Array - Hash - Linked List and Search for hash in an array of hashes .

any

The any function will return true if any of the given values satisfies the given condition. It is shown in the article Filtering values using Perl grep as a better solution.

It is also used in the example showing how to create a testing module and how to implement 'is_any' to test multiple expected values .

all

The all function will return true if all the supplied values satisfy the given condition. It can be seen in the article Check several regexes on many strings .

reduce

The reduce function might be familiar to you from the MapReduce programming model that was lauded around "BigData". It makes it provides a way to summarize data in an easy way. Implementing factorial in Perl - n! is a good and simple example. It is also used in the Fast lookup by name or by date - Array - Hash - Linked List article.

[Nov 21, 2019] Tux.nl - Style and Layout

Nov 21, 2019 | tux.nl

Why my style is best better

I will try to explain the logic behind the style decisions taken over that last 35+ years of programming in different languages.

About programming style and layout there are as many opinions as there are people. Most important in my opinion is to think about the reasoning behind what you, your team or your company chooses to follow as guides.

I seriously think that way too many (young) programmers leave school, brainwashed with GNU-style coding without realizing that the amount of indentation and the placing of braces, brackets and parentheses were well thought about.

Several well known styles (including mine) are discussed at wikimedia . It is worth reading through them to see the pros and cons of each.

For me personally, the GNU coding style is one of the reasons I do NOT contribute a lot to these projects. The style does not fit my logic, and if I send patches that are rejected simply because I wrote them in a style/layout that I think is way better because I then understand the underlying logic, I give up.

Here I will take a tour through what I think is the only correct way of (perl) code layout, and why. Most of this can be achieved with Perl::Tidy and a correct .perltidyrc . I'll use their configuration definitions as a guide.

Indentation in code blocks
Opening Block Brace Right or Left
Braces Left
Because braces are just syntactic sugar to keep a block together, it should visually also bind to the block, and not to the conditional. As the closing brace - or END in languages like PASCAL - is visually showing me the end of the block, it should obviously have the same indent as the block itself. An advantage is that the alignment of the closing brace with the block emphasizes the fact that the entire block is conceptually (as well as programmatically) a single compound statement.
In other words: I see the braces being part of the block, and as all statements inside a block share the same indentation, in my opinion the brace - being part of the block - should have the same indentation too.
  • Indent width is 4, tabs are allowed (when set to 8). I prefer having it being spaces only, but as I cannot see the difference with good editors, I do not really care.
  • Opening brace should be on the same line as the conditional
  • Block should be indented
  • Closing brace should have the same indent as the block
  if ($flag eq "a") {
      $anchor = $header;
      }
This style is also referred to as Ratliff style on wikipedia or Banner style on wikimedia.
Continuation Indentation
  if ($flag eq "a") {
      $anchor = substr ($header, 0, 6) .
                substr ($char_list, $place_1, 1) .
                substr ($char_list, $place_2, 1);
      }
Or, also acceptable:
  if ($flag eq "a") {
      $anchor =
          substr ($header, 0, 6) .
          substr ($char_list, $place_1, 1) .
          substr ($char_list, $place_2, 1);
      }
Braces Right
  if ($bigwasteofspace1 && $bigwasteofspace2 ||
      $bigwasteofspace3 && $bigwasteofspace4) {
      big_waste_of_time ();
      }
also acceptable:
  if (   $bigwasteofspace1 && $bigwasteofspace2
      || $bigwasteofspace3 && $bigwasteofspace4) {
      big_waste_of_time ();
      }
also acceptable:
  if (  $bigwasteofspace1 && $bigwasteofspace2 ||
        $bigwasteofspace3 && $bigwasteofspace4) {
      big_waste_of_time ();
      }
(No) Cuddled Else
Of course cuddled else is not the way to go, as it makes removing either branch more difficult and makes the indent of the closing brace go wrong. The only right way to use if/else indent is uncuddled:
  if ($flag eq "h") {
      $headers = 0;
      }
  elsif ($flag eq "f") {
      $sectiontype = 3;
      }
  else {
      print "invalid option: " . substr ($arg, $i, 1) . "\n";
      dohelp ();
      }
Vertical tightness
  sub _directives
  {
      {   ENDIF => \&_endif,
          IF    => \&_if,
          };
      } # _directives
the opening brace of a sub may optionally be put on a new line. If so, it should be in column one, for all those that use 'vi' or one of it's clones, so }, {, ]], and [[ work as expected.
if the opening brace is on the same line, which I prefer, it requires a single leading space
  sub _directives {
      {   ENDIF => \&_endif,
          IF    => \&_if,
          };
      } # _directives
Indentation Style for Other Containers
Opening Vertical Tightness
  $dbh = DBI->connect (undef, undef, undef, {
      PrintError => 0,
      RaiseError => 1,
      });
  if (!defined (start_slip ($DEVICE, $PHONE,  $ACCOUNT, $PASSWORD,
                            $LOCAL,  $REMOTE, $NETMASK, $MTU)) &&
       $continuation_flag) {
      do_something_about_it ();
      }
Closing Token Placement
  my @month_of_year = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
                        );
also acceptable:
  my @month_of_year = (qw(
      Jan Feb Mar Apr May Jun
      Jul Aug Sep Oct Nov Dec
      ));
As with the closing brace of a block, the closing parenthesis belongs to the data in the container it closes, and thus should have the same indentation.
Define Horizontal Tightness
Of course function <space> <paren> <no-space> <first-arg> <comma> <space>
  if ((my $duration = travel ($target, $means)) > 1200) {
One of my pet-peeves. Having white-space between the function name and its opening parenthesis is the best match to how we think. As an example, if I would ask someone to describe his/her day, he/she might answer
  I woke up
  I freshened myself
  I had breakfast
  I got to work
  I worked
  I had lunch
  I worked again
  I went home
  I had diner
  I watched TV
  I brushed my teeth
  I went to bed
In computer-speak
  wake_up ();
  wash ($self);
  eat ("breakfast");
  goto ("work")
  work ();
  eat ("lunch");
  work ();
  goto ("home");
  eat ("diner");
  watch_tv ();
  wash ($teeth);
  sleep ();
In which the seasoned programmer might see
  for $day in (qw( Mon Tue Wed Thu Fri )) {
     wake_up ();
     wash ($self);
     eat ("breakfast");
     :
     :
Or, more extreme to show the sequence of actions
  for $day in (qw( Mon Tue Wed Thu Fri )) {
     wake_up ();
     wash    ($self);
     eat     ("breakfast");
     :
     :
Where it, IMHO, clearly shows that the actions are far more important than what it takes to perform the action. When I read through the process, I don't care about what transport the person uses to get to work and if eggs are part of the breakfast. These are the parameters to the actions
  for $day in (qw( Mon Tue Wed Thu Fri )) {
     wake_up ();
     wash    ($day eq "Fri" ? "bath" : "shower", water_temp => "47");
     eat     (type   => "breakfast", eggs  => 2, toast => 4, Tea => "yes");
     travel  (target => $work,       means => "train");
     :
     :
I will only have a look at the function's argument if I need to. In reading that I eat , I see what action is taken. That's enough for understanding the program flow. The arguments to the function have to be grouped together using parenthesis for the function to know that all the arguments are for the function: the parenthesis are there to group the arguments, not to make the function a function so the parenthesis belong to the arguments and not to the function and therefor are to be close to the arguments ant not to the function.
Arguments are separated by a comma and a space, just to separate the arguments more for better readability
  my $width = $col[$j + $k] - $col[$j];

  my %bf = map { $_ => -M $_ } grep { m/\.deb$/ } dirents ".";
Statement modifiers
  $work_done and go_home ();
A rule of thumb is to NEVER use statement modifiers like
  go_home () unless $work_done; # WRONG!
As it will draw the attention to going home (unconditionally) instead of to the condition, which is more important. This is especially annoying when using exit, die, croak or return. Any of these will visually end the current scope, so you do not have to read on. Unless there is a statement modifier and you need to re-read the entire section.
No else after return/exit/die/croak/throw
  if (expression) {
      return;
      }
  else {
      return 42;
      }
As any of return, exit, die, croak, or throw will immediately exit the current scope, the mind will read the code as to stop processing it right there, which is exactly what those keywords are for.
In an if/else construct, the code after the construct is supposed to be executed when either if the if/else branches where followed. If the if-branch exits the current scope, there is no need to run the code after the construct, so the else is useless.
This is the main reason why these keywords should never have a statement modifier (and no, you cannot come up with a valid exception to this rule).
Statement Termination Semicolon Spaces
  my $i = 1;
For Loop Semicolon Spaces
  for (@a = @$ap, $u = shift @a; @a; $u = $v) {
Block Comment Indentation
  • If comment is aligned to the left margin, leave it there
  • If the original comment was indented, match the indent to the surrounding code.
  • Never reformat comments itself. Do not wrap
Outdenting Long Quotes
  if ($source_stream) {
      if (@ARGV > 0) {
          die "You may not specify any filenames when a source array is given\n";
          }
      }
  if ($source_stream) {
      if (@ARGV > 0) {
          die "You may not specify any filenames ".
              "when a source array is given\n";
          }
      }
  for (@methods) {
      push @results, {
          name => $_->name,
          help => $_->help,
          };
      }

[Nov 21, 2019] Replaying debugger commands from history

Nov 21, 2019 | perlmonks.org

LanX (Archbishop) on Nov 20, 2019 at 15:59 UTC

Re: Replaying debugger commands from history

Sure!

Have a look at the docs in perldebug#Debugger-Customization concerning

@DB::typeahead

like

sub afterinit { push @DB::typeahead, "b 4", "b 6"; }

IIRC it should be either settable

[Nov 21, 2019] Can the Perl debugger save the ReadLine history to a file?

Nov 21, 2019 | stackoverflow.com

Ask Question Asked 8 years, 5 months ago Active 6 years ago Viewed 941 times 10 2


eli ,Jun 7, 2018 at 14:13

I work quit a bit with lib ReadLine and the lib Perl Readline.

Yet, the Perl debugger refuses to save the session command line history.

Thus, each time I invoke the debugger I lose all of my previous history.

Does anyone know how to have the Perl debugger save, and hopefully, append session history similar to the bash HISTORYFILE ?

mirod ,Jun 22, 2011 at 10:31

The way I do this is by having the following line in my ~/.perldb file:

&parse_options("HistFile=$ENV{HOME}/.perldb.hist");

Debugger commands are then stored in ~/.perldb.hist and accessible across sessions.

ysth ,Jul 13, 2011 at 9:37

Add parse_options("TTY=/dev/stdin ReadLine=0"); to .perldb, then:
rlwrap -H .perl_history perl -d ...

mephinet ,Feb 21, 2012 at 12:37

$ export PERLDB_OPTS=HistFile=$HOME/.perldb.history

,

I did the following:

1) Created ~/.perldb , which did not exist previously.

2) Added &parse_options("HistFile=$ENV{HOME}/.perldb.hist"); from mirod's answer.

3) Added export PERLDB_OPTS=HistFile=$HOME/.perldb.history to ~/.bashrc from mephinet's answer.

4) Ran source .bashrc

5) Ran perl -d my program.pl , and got this warning/error

perldb: Must not source insecure rcfile /home/ics/.perldb.
        You or the superuser must be the owner, and it must not 
        be writable by anyone but its owner.

6) I protected ~/.perldb with owner rw chmod 700 ~/.perldb , and the error went away.

[Nov 21, 2019] Fast common substring matching

Nov 21, 2019 | perlmonks.org

This code was written as a solution to the problem posed in Search for identical substrings . As best I can tell it runs about 3 million times faster than the original code.

The code reads a series of strings and searches them for the longest substring between any pair of strings. In the original problem there were 300 strings about 3K long each. A test set comprising 6 strings was used to test the code with the result given below.

Someone with Perl module creation and publication experience could wrap this up and publish it if they wish.

use strict;
use warnings;
use Time::HiRes;
use List::Util qw(min max);

my $allLCS = 1;
my $subStrSize = 8; # Determines minimum match length. Should be a power of 2
# and less than half the minimum interesting match length. The larger this value
# the faster the search runs.

if (@ARGV != 1)
    {
    print "Finds longest matching substring between any pair of test strings\n";
    print "the given file. Pairs of lines are expected with the first of a\n";
    print "pair being the string name and the second the test string.";
    exit (1);
    }

# Read in the strings
my @strings;
while ()
  {
  chomp;
  my $strName = $_;
  $_ = ;
  chomp;
  push @strings, [$strName, $_];
  }

my $lastStr = @strings - 1;
my @bestMatches = [(0, 0, 0, 0, 0)]; # Best match details
my $longest = 0; # Best match length so far (unexpanded)

my $startTime = [Time::HiRes::gettimeofday ()];

# Do the search
for (0..$lastStr)
  {
  my $curStr = $_;
  my @subStrs;
  my $source = $strings[$curStr][1];
  my $sourceName = $strings[$curStr][0];

  for (my $i = 0; $i  0;
        push @localBests, [@test] if $dm >= 0;
        $offset = $test[3] + $test[4];

        next if $test[4]  0;
        push @bestMatches, [@test];
        }
        continue {++$offset;}
      }

    next if ! $allLCS;

    if (! @localBests)
      {
      print "Didn't find LCS for $sourceName and $targetName\n";
      next;
      }

    for (@localBests)
      {
      my @curr = @$_;
      printf "%03d:%03d L[%4d] (%4d %4d)\n",
        $curr[0], $curr[1], $curr[4], $curr[2], $curr[3];
      }
    }
  }

print "Completed in " . Time::HiRes::tv_interval ($startTime) . "\n";
for (@bestMatches)
  {
  my @curr = @$_;
  printf "Best match: %s - %s. %d characters starting at %d and %d.\n",
    $strings[$curr[0]][0], $strings[$curr[1]][0], $curr[4], $curr[2], $curr[3];
  }


sub expandMatch
{
my ($index1, $index2, $str1Start, $str2Start, $matchLen) = @_;
my $maxMatch = max (0, min ($str1Start, $subStrSize + 10, $str2Start));
my $matchStr1 = substr ($strings[$index1][1], $str1Start - $maxMatch, $maxMatch);
my $matchStr2 = substr ($strings[$index2][1], $str2Start - $maxMatch, $maxMatch);

($matchStr1 ^ $matchStr2) =~ /\0*$/;
my $adj = $+[0] - $-[0];
$matchLen += $adj;
$str1Start -= $adj;
$str2Start -= $adj;

return ($index1, $index2, $str1Start, $str2Start, $matchLen);
}



Output using bioMan 's six string sample:

Completed in 0.010486 Best match: >string 1 - >string 3 . 1271 characters starting at 82 an + d 82. [download]

[Nov 15, 2019] Why do many people assume OOP is on the decline?

Nov 15, 2019 | www.quora.com

Daniel Korenblum

Daniel Korenblum , works at Bayes Impact Updated May 25, 2015 There are many reasons why non-OOP languages and paradigms/practices are on the rise, contributing to the relative decline of OOP.

First off, there are a few things about OOP that many people don't like, which makes them interested in learning and using other approaches. Below are some references from the OOP wiki article:

  1. Cardelli, Luca (1996). "Bad Engineering Properties of Object-Oriented Languages". ACM Comput. Surv. (ACM) 28 (4es): 150. doi:10.1145/242224.242415. ISSN 0360-0300. Retrieved 21 April 2010.
  2. Armstrong, Joe. In Coders at Work: Reflections on the Craft of Programming. Peter Seibel, ed. Codersatwork.com , Accessed 13 November 2009.
  3. Stepanov, Alexander. "STLport: An Interview with A. Stepanov". Retrieved 21 April 2010.
  4. Rich Hickey, JVM Languages Summit 2009 keynote, Are We There Yet? November 2009. (edited)
taken from:

Object-oriented programming

Also see this post and discussion on hackernews:

Object Oriented Programming is an expensive disaster which must end

One of the comments therein linked a few other good wikipedia articles which also provide relevant discussion on increasingly-popular alternatives to OOP:

  1. Modularity and design-by-contract are better implemented by module systems ( Standard ML )
  2. Encapsulation is better served by lexical scope ( http://en.wikipedia.org/wiki/Sco... )
  3. Data is better modelled by algebraic datatypes ( Algebraic data type )
  4. Type-checking is better performed structurally ( Structural type system )
  5. Polymorphism is better handled by first-class functions ( First-class function ) and parametricity ( Parametric polymorphism )

Personally, I sometimes think that OOP is a bit like an antique car. Sure, it has a bigger engine and fins and lots of chrome etc., it's fun to drive around, and it does look pretty. It is good for some applications, all kidding aside. The real question is not whether it's useful or not, but for how many projects?

When I'm done building an OOP application, it's like a large and elaborate structure. Changing the way objects are connected and organized can be hard, and the design choices of the past tend to become "frozen" or locked in place for all future times. Is this the best choice for every application? Probably not.

If you want to drive 500-5000 miles a week in a car that you can fix yourself without special ordering any parts, it's probably better to go with a Honda or something more easily adaptable than an antique vehicle-with-fins.

Finally, the best example is the growth of JavaScript as a language (officially called EcmaScript now?). Although JavaScript/EcmaScript (JS/ES) is not a pure functional programming language, it is much more "functional" than "OOP" in its design. JS/ES was the first mainstream language to promote the use of functional programming concepts such as higher-order functions, currying, and monads.

The recent growth of the JS/ES open-source community has not only been impressive in its extent but also unexpected from the standpoint of many established programmers. This is partly evidenced by the overwhelming number of active repositories on Github using JavaScript/EcmaScript:

Top Github Languages of 2014 (So far)

Because JS/ES treats both functions and objects as structs/hashes, it encourages us to blur the line dividing them in our minds. This is a division that many other languages impose - "there are functions and there are objects/variables, and they are different".

This seemingly minor (and often confusing) design choice enables a lot of flexibility and power. In part this seemingly tiny detail has enabled JS/ES to achieve its meteoric growth between 2005-2015.

This partially explains the rise of JS/ES and the corresponding relative decline of OOP. OOP had become a "standard" or "fixed" way of doing things for a while, and there will probably always be a time and place for OOP. But as programmers we should avoid getting too stuck in one way of thinking / doing things, because different applications may require different approaches.

Above and beyond the OOP-vs-non-OOP debate, one of our main goals as engineers should be custom-tailoring our designs by skillfully choosing the most appropriate programming paradigm(s) for each distinct type of application, in order to maximize the "bang for the buck" that our software provides.

Although this is something most engineers can agree on, we still have a long way to go until we reach some sort of consensus about how best to teach and hone these skills. This is not only a challenge for us as programmers today, but also a huge opportunity for the next generation of educators to create better guidelines and best practices than the current OOP-centric pedagogical system.

Here are a couple of good books that elaborates on these ideas and techniques in more detail. They are free-to-read online:

  1. https://leanpub.com/javascriptal...
  2. https://leanpub.com/javascript-s...
Mike MacHenry , software engineer, improv comedian, maker Answered Feb 14, 2015 · Author has 286 answers and 513.7k answer views Because the phrase itself was over hyped to an extrodinary degree. Then as is common with over hyped things many other things took on that phrase as a name. Then people got confused and stopped calling what they are don't OOP.

Yes I think OOP ( the phrase ) is on the decline because people are becoming more educated about the topic.

It's like, artificial intelligence, now that I think about it. There aren't many people these days that say they do AI to anyone but the laymen. They would say they do machine learning or natural language processing or something else. These are fields that the vastly over hyped and really nebulous term AI used to describe but then AI ( the term ) experienced a sharp decline while these very concrete fields continued to flourish.

[Nov 15, 2019] Why is Perl so hated and still commonly used? And why should I learn it?

Notable quotes:
"... Per Damien Conway’s recommendations, I always unpack all the arguments from @_in the first line of a subroutine, which ends up looking just like a subroutine signature. (I almost never use shift for this purpose.) ..."
"... Perl bashing is largely hear-say. People hear something and they say it. It doesn't require a great deal of thought. ..."
"... It may not be as common as the usual gang of languages, but there's an enormous amount of work done in Perl. ..."
Nov 05, 2017 | www.quora.com

Joe Zbiciak , Employed Updated Nov 5 2017 · Author has 2k answers and 7.3m answer views

Perl bashing is popular sport among a particularly vocal crowd.

Perl is extremely flexible. Perl holds up TIMTOWTDI ( There Is More Than One Way To Do It ) as a virtue. Larry Wall's Twitter handle is @TimToady, for goodness sake!

That flexibility makes it extremely powerful. It also makes it extremely easy to write code that nobody else can understand. (Hence, Tim Toady Bicarbonate.)

You can pack a lot of punch in a one-liner in Perl:

  1. print $fo map { sprintf ( " .pword 0x%.6X\n" , $_ ) } unpack ( "n*" , $data );

That one-liner takes a block of raw data (in $data ), expands it to an array of values, and th...

Joachim Pense , Perl is my language of choice Answered Nov 4, 2017 · Author has 6.1k answers and 7.1m answer views

It is still used, but its usage is declining. People use Python today in situations when they would have used Perl ten years ago.

The problem is that Perl is extremely pragmatic. It is designed to be “a language to get your job done”, and it does that well; however, that led to rejection by language formalists. However, Perl is very well designed, only it is well designed for professionals who grab in the dark expecting that at this place there should be a button to do the desired functionality, and indeed, there will be the button. It is much safer to use than for example C (the sharp knife that was delivered without a handle), but it is easy to produce quite messy code with it if you are a newbie who doesn’t understand/feel the principles of Perl. In the 90s and 2000s, it was the goto web language, so the web was full of terrible programs written by those newbies, and that led to the bad reputation.

Strangely enough, PHP, which is frowned upon a lot by Perl programmers, won the favour of the noobs, but never got the general bad reputation; in fact it is missing the design principles I mentioned, that language is just a product of adhockery.

But today, Perl went back to its status as a niche language, and you cannot mention it in presence of a lady, so to speak. Its support is slowly waning; I’d suggest to learn Python, but don’t force me to learn it as well.

John Robinson , Software Engineer Answered Nov 4, 2017 · Author has 416 answers and 92.9k answer views

You should learn things that make your life easier or better. I am not an excellent Perl user, but it is usually my go-to scripting language for important projects. The syntax is difficult, and it's very easy to forget how to use it when you take significant time away from it.

That being said, I love how regular expressions work in Perl. I can use sed like commands $myvar =~ s/old/new/g for string replacement when processing or filtering strings. It's much nicer than other languages imo.

I also like Perls foreach loops and its data structures.

I tried writing a program of moderate length in Python and it just seemed to be taking up too much space. I stopped part way though and switched to Perl. I got the whole thing completed in much less space (lines), and seemed to have an easier time doing it.

I am not a super fanboy, but it has just always worked for me in the past, and I can't outright discount it because of that.

Also, look up CPAN modules. The installation of those for me on GNU is a breeze.

My last scripting project I did in Python and it went very well. I will probably shift to Python more in the future, because I would like to build a stronger basis of knowledge with the modules and basics of Python so that I can hop into it and create some powerful stuff when needed. Ie I want to focus on 1–3 languages, and learn them to a higher level instead of being "just ok" with 5–7.

Gary Puckering , Fluent in C#, Python, and perl; rusty in C/C++ and too many others to count Answered Apr 25, 2018 · Author has 1.1k answers and 2.5m answer views

Why is Perl so hated and not commonly used?

I think there are several reasons why Perl has a lot of detractors

  1. Sigils . A lot of programmers seem to hate the $@% sigils! If you are coming from a strongly typed language like C/C++, and also hate things like Hungarian notation, you won’t like sigils.
  2. One liners. As others have commented, writing dense and even obfuscated code rose to the level of sport within the Perl community. The same thing happened, years earlier, in the APL community. Programmers and managers saw that you could write unmaintainable code, and that helped instill a fear that it was unavoidable and that perhaps the language was flawed because it didn’t discourage the practice.
  3. Auto-magic . The programming language PL/I, which attempted to combine the best of COBOL and FORTRAN, went absolutely crazy with default behaviors. I remember reading an article in the 1970’s where programming in PL/I was described as being like flying a Boeing 747. The cockpit is filled with hundreds of buttons, knobs, switches and levers. The autopilot does most of the work, but trying to figure out the interaction between it and things you manually set can be bewildering. Perl, to some extent, suffers from the same problem. In Perl 5, without enabling warnings and strict, variables spring into life simply by naming them. A typo can instantiate and entirely new variable. Hashes get new keys simply by an attempt to access a key. You can increment a scalar that contains a string and it’ll try to generate a sequence using the string as a pattern (e.g. a, b, c … z, aa, ab …). If you come from a language where you control everything, all this auto-magic stuff can really bite you in the ass.
  4. An odd object-oriented syntax. Until Moose (and now Moo and Mouse) came along, writing classes in Perl meant using keywords like package and bless, as well as rolling all your own accessor methods. If you come from C++, Java , Python or just about any other language supporting OO your first question is going to be: where’s the friggin’ class statement!
  5. Dynamic typing . Some people like it. Some hate it. There are modules that let you add typing I’d you wish, though it’ll only be enforced at run time.
  6. No subroutine signatures . Although Perl 5 now supports subroutine signatures, they are still considered “experimental”. This is a turn-off for most programmers who are used to them. Per Damien Conway’s recommendations, I always unpack all the arguments from @_in the first line of a subroutine, which ends up looking just like a subroutine signature. (I almost never use shift for this purpose.)
  7. Lots of magic symbols . Although you can use English names, and should do so for more maintainable code, many Perl programmers stick to using special names like $_, $’, $; etc. This makes Perl code look very cryptic, and increases your cognitive load when working with the language. It’s a lot to remember. But if you use the English names, you can largely avoid this issue.
  8. Perl 6 is a discontinuous evolution . Although Perl 5 continues to evolve, and some of the advances that have been put in Perl 6 have been added to Perl 5, the lack of,upward compatibility between 5 and 6 creates uncertainly about its future.

And why should I learn it?

Despite the above, you can write maintainable code in Perl by following Damian Comways’s Perl Best Practices. The utility perlcritic can be used to help train yourself to write better Perl code.

Perl is multi-paradigm. In execution, it’s faster than Python. It has a superb ecosystem in cpan , where you can find a module to help you solve almost every imaginable problem. For command line utilities, file system administration, database administration, data extraction-transformation-loading tasks, batch processes, connecting disparate systems, and quick and dirty scripts, it’s often the best tool for the job.

I frequently use Perl in connection with Excel. You can do a lot in Excel, and it provides a great interactive UI. But complex formulas can be a pain to get right, and it can be tedious to write code in VBA. Often, I find it much quicker to just copy cells to the clipboard, switch to a command shell, run a Perl script over the data, sending the results to the clipboard, switch back to Excel, and then paste the results in situ or in a new location.

Perl is also deep. It does a good job of supporting imperative programming, OOP, and functional programming. For more on the latter, see the book Higher-Order Perl .

Perl is powerful. Perl is fast. Perl is an effective tool to have in your toolkit. Those are all good reasons to learn it.

Reed White , former Engineer at Hewlett-Packard (1978-2000) Answered Nov 7, 2017 · Author has 2.3k answers and 380.8k answer views

Yes, Perl takes verbal abuse; but in truth, it is an extremely powerful, reliable language. In my opinion, one of its outstanding characteristics is that you don't need much knowledge before you can write useful programs. As time goes by, you gradually learn the real power of the language.

However, because Perl-bashing is popular, you might better put your efforts into learning Python, which is also quite capable.

Richard Conto , Programmer in multiple languages. Debugger in even more Answered Dec 18, 2017 · Author has 5.9k answers and 4.3m answer views

Perl bashing is largely hear-say. People hear something and they say it. It doesn't require a great deal of thought.

As for Perl not commonly being used - that's BS. It may not be as common as the usual gang of languages, but there's an enormous amount of work done in Perl.

As for you you should learn Perl, it's for the same reason you would learn any other language - it helps you solve a particular problem better than another language available. And yes, that can be a very subjective decision to make.

Randal L. Schwartz , Literally "wrote the books" on it Answered Mar 3, 2018 · Author has 108 answers and 90.5k answer views

The truth is, that by any metric, more Perl is being done today than during the dot com boom. It's just a somewhat smaller piece of a much bigger pie. In fact, I've heard from some hiring managers that there's actually a shortage of Perl programmers, and not just for maintaining projects, but for new greenfield deploys.

[Nov 15, 2019] Why are Unix system administrators still using Perl for scripting when they could use Python - Quora

Nov 15, 2019 | www.quora.com

Why are Unix system administrators still using Perl for scripting when they could use Python? Update Cancel

a OYLu d zEv ORPC b dRl y q nyXNY D AZ a eSr t gpl a yTipB d lH o xE g ookz H Tr Q voRm . iKPKM c YuOhH o M m HVViy Visualize Docker performance and usage in real time. Track Docker health and usage alongside custom metrics from your apps and services. Try Datadog for free. Learn More You dismissed this ad. The feedback you provide will help us show you more relevant content in the future. Undo Answer Wiki 12 Answers Joshua Day

Joshua Day , Currently developing reporting and testing tools for linux Updated Apr 26 · Author has 83 answers and 71k answer views

There are several reasons and ill try to name a few.

  1. Perl syntax and semantics closely resembles shell languages that are part of core Unix systems like sed, awk, and bash. Of these languages at least bash knowledge is required to administer a Unix system anyway.
  2. Perl was designed to replace or improve the shell languages in Unix/linux by combining all their best features into a single language whereby an administrator can write a complex script with a single language instead of 3 languages. It was essentially designed for Unix/linux system administration.
  3. Perl regular expressions (text manipulation) were modeled off of sed and then drastically improved upon to the extent that subsequent languages like python have borrowed the syntax because of just how powerful it is. This is infinitely powerful on a unix system because the entire OS is controlled using textual data and files. No other language ever devised has implemented regular expressions as gracefully as perl and that includes the beloved python. Only in perl is regex integrated with such natural syntax.
  4. Perl typically comes preinstalled on Unix and linux systems and is practically considered part of the collection of softwares that define such a system.
  5. Thousands of apps written for Unix and linux utilize the unique properties of this language to accomplish any number of tasks. A Unix/linux sysadmin must be somewhat familiar with perl to be effective at all. To remove the language would take considerable effort for most systems to the extent that it's not practical.. Therefore with regard to this environment Perl will remain for years to come.
  6. Perl's module archive called CPAN already contains a massive quantity of modules geared directly for unix systems. If you use Perl for your administration tasks you can capitalize on these modules. These are not newly written and untested modules. These libraries have been controlling Unix systems for 20 years reliably and the pinnacle of stability in Unix systems running across the world.
  7. Perl is particularly good at glueing other software together. It can take the output of one application and manipulate it into a format that is easily consumable by another, mostly due to its simplistic text manipulation syntax. This has made Perl the number 1 glue language in the world. There are millions of softwares around the world that are talking to each other even though they were not designed to do so. This is in large part because of Perl. This particular niche will probably decline as standardization of interchange formats and APIs improves but it will never go away.

I hope this helps you understand why perl is so prominent for Unix administrators. These features may not seem so obviously valuable on windows systems and the like. However on Unix systems this language comes alive like no other.

[Nov 14, 2019] perl - package variable scope in module subroutine - Stack Overflow

Nov 14, 2019 | stackoverflow.com

package variable scope in module subroutine Ask Question Asked 7 years, 7 months ago Active 7 years, 7 months ago Viewed 20k times 8 1


brian d foy ,Jul 17, 2014 at 17:54

How do I change the value of a variable in the package used by a module so that subroutines in that module can use it?

Here's my test case:

testmodule.pm:

package testmodule;

use strict;
use warnings;
require Exporter;

our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);

@ISA = qw(Exporter);
@EXPORT = qw(testsub);

my $greeting = "hello testmodule";
my $var2;

sub testsub {
    printf "__PACKAGE__: %s\n", __PACKAGE__;
    printf "\$main::greeting: %s\n", $main::greeting;
    printf "\$greeting: %s\n", $greeting;
    printf "\$testmodule::greeting: %s\n", $testmodule::greeting;
    printf "\$var2: %s\n", $var2;
} # End testsub
1;

testscript.pl:

#!/usr/bin/perl -w
use strict;
use warnings;
use testmodule;

our $greeting = "hello main";
my $var2 = "my var2 in testscript";

$testmodule::greeting = "hello testmodule from testscript";
$testmodule::var2 = "hello var2 from testscript";

testsub();

output:

Name "testmodule::var2" used only once: possible typo at ./testscript.pl line 11.
__PACKAGE__: testmodule
$main::greeting: hello main
$greeting: hello testmodule
$testmodule::greeting: hello testmodule from testscript
Use of uninitialized value $var2 in printf at testmodule.pm line 20.
$var2:

I expected $greeting and $testmodule::greeting to be the same since the package of the subroutine is testmodule .

I guess this has something to do with the way use d modules are eval d as if in a BEGIN block, but I'd like to understand it better.

I was hoping to set the value of the variable from the main script and use it in the module's subroutine without using the fully-qualified name of the variable.

perl-user ,Sep 5, 2013 at 13:58

As you found out, when you use my , you are creating a locally scoped non-package variable. To create a package variable, you use our and not my :
my $foo = "this is a locally scoped, non-package variable";
our $bar = "This is a package variable that's visible in the entire package";

Even better:

{
   my $foo = "This variable is only available in this block";
   our $bar = "This variable is available in the whole package":
}

print "$foo\n";    #Whoops! Undefined variable
print "$bar\n";    #Bar is still defined even out of the block

When you don't put use strict in your program, all variables defined are package variables. That's why when you don't put it, it works the way you think it should and putting it in breaks your program.

However, as you can see in the following example, using our will solve your dilemma:

File Local/Foo.pm
#! /usr/local/bin perl
package Local::Foo;

use strict;
use warnings;
use feature qw(say);

use Exporter 'import';
our @EXPORT = qw(testme);

our $bar = "This is the package's bar value!";
sub testme {

    # $foo is a locally scoped, non-package variable. It's undefined and an error
    say qq(The value of \$main::foo is "$main::foo");

    # $bar is defined in package main::, and will print out
    say qq(The value of \$main::bar is "$main::bar");

    # These both refer to $Local::Foo::bar
    say qq(The value of \$Local::Foo::bar is "$Local::Foo::bar");
    say qq(The value of bar is "$bar");
}

1;
File test.pl
#! /usr/local/bin perl
use strict;
use warnings;
use feature qw(say);
use Local::Foo;

my $foo = "This is foo";
our $bar = "This is bar";
testme;

say "";
$Local::Foo::bar = "This is the NEW value for the package's bar";
testme

And, the output is:

Use of uninitialized value $foo in concatenation (.) or string at Local/Foo.pm line 14.
The value of $main::foo is ""
The value of $main::bar is "This is bar"
The value of $Local::Foo::bar is "This is the package's bar value!"
The value of bar is "This is the package's bar value!"

Use of uninitialized value $foo in concatenation (.) or string at Local/Foo.pm line 14.
The value of $main::foo is ""
The value of $main::bar is "This is bar"
The value of $Local::Foo::bar is "This is the NEW value for the package's bar"
The value of bar is "This is the NEW value for the package's bar"

The error message you're getting is the result of $foo being a local variable, and thus isn't visible inside the package. Meanwhile, $bar is a package variable and is visible.

Sometimes, it can be a bit tricky:

if ($bar -eq "one") {
   my $foo = 1;
}
else {
   my $foo = 2;
}

print "Foo = $foo\n";

That doesn't work because $foo only bas a value inside the if block. You have to do this:

my $foo;
if ($bar -eq "one") {
   $foo = 1;
}
else {
  $foo = 2;
}

print "Foo = $foo\n"; #This works!

Yes, it can be a bit to get your head wrapped around it initially, but the use of use strict; and use warnings; is now de rigueur and for good reasons. The use of use strict; and use warnings; probably has eliminated 90% of the mistakes people make in Perl. You can't make a mistake of setting the value of $foo in one part of the program, and attempting to use $Foo in another. It's one of the things I really miss in Python.

> ,

After reading Variable Scoping in Perl: the basics more carefully, I realized that a variable declared with my isn't in the current package. For example, in a simple script with no modules if I declare my $var = "hello" $main::var still doesn't have a value.

The way that this applies in this case is in the module. Since my $greeting is declared in the file, that hides the package's version of $greeting and that's the value which the subroutine sees. If I don't declare the variable first, the subroutine would see the package variable, but it doesn't get that far because I use strict .

If I don't use strict and don't declare my $greeting , it works as I would have expected. Another way to get the intended value and not break use strict is to use our $greeting . The difference being that my declares a variable in the current scope while our declares a variable in the current package .

[Nov 13, 2019] How fast is Perl s smartmatch operator when searching for a scalar in an array

Nov 13, 2019 | stackoverflow.com

Paul Tomblin ,Oct 19, 2010 at 13:38

I want to repeatedly search for values in an array that does not change.

So far, I have been doing it this way: I put the values in a hash (so I have an array and a hash with essentially the same contents) and I search the hash using exists .

I don't like having two different variables (the array and the hash) that both store the same thing; however, the hash is much faster for searching.

I found out that there is a ~~ (smartmatch) operator in Perl 5.10. How efficient is it when searching for a scalar in an array?

> ,

If you want to search for a single scalar in an array, you can use List::Util 's first subroutine. It stops as soon as it knows the answer. I don't expect this to be faster than a hash lookup if you already have the hash , but when you consider creating the hash and having it in memory, it might be more convenient for you to just search the array you already have.

As for the smarts of the smart-match operator, if you want to see how smart it is, test it. :)

There are at least three cases you want to examine. The worst case is that every element you want to find is at the end. The best case is that every element you want to find is at the beginning. The likely case is that the elements you want to find average out to being in the middle.

Now, before I start this benchmark, I expect that if the smart match can short circuit (and it can; its documented in perlsyn ), that the best case times will stay the same despite the array size, while the other ones get increasingly worse. If it can't short circuit and has to scan the entire array every time, there should be no difference in the times because every case involves the same amount of work.

Here's a benchmark:

#!perl
use 5.12.2;
use strict;
use warnings;

use Benchmark qw(cmpthese);

my @hits = qw(A B C);
my @base = qw(one two three four five six) x ( $ARGV[0] || 1 );

my @at_end       = ( @base, @hits );
my @at_beginning = ( @hits, @base );

my @in_middle = @base;
splice @in_middle, int( @in_middle / 2 ), 0, @hits;

my @random = @base;
foreach my $item ( @hits ) {
    my $index = int rand @random;
    splice @random, $index, 0, $item;
    }

sub count {
    my( $hits, $candidates ) = @_;

    my $count;
    foreach ( @$hits ) { when( $candidates ) { $count++ } }
    $count;
    }

cmpthese(-5, {
    hits_beginning => sub { my $count = count( \@hits, \@at_beginning ) },
    hits_end       => sub { my $count = count( \@hits, \@at_end ) },
    hits_middle    => sub { my $count = count( \@hits, \@in_middle ) },
    hits_random    => sub { my $count = count( \@hits, \@random ) },
    control        => sub { my $count = count( [], [] ) },
  }
);
div class="answercell post-layout--right

,

Here's how the various parts did. Note that this is a logarithmic plot on both axes, so the slopes of the plunging lines aren't as close as they look:

So, it looks like the smart match operator is a bit smart, but that doesn't really help you because you still might have to scan the entire array. You probably don't know ahead of time where you'll find your elements. I expect a hash will perform the same as the best case smart match, even if you have to give up some memory for it.


Okay, so the smart match being smart times two is great, but the real question is "Should I use it?". The alternative is a hash lookup, and it's been bugging me that I haven't considered that case.

As with any benchmark, I start off thinking about what the results might be before I actually test them. I expect that if I already have the hash, looking up a value is going to be lightning fast. That case isn't a problem. I'm more interested in the case where I don't have the hash yet. How quickly can I make the hash and lookup a key? I expect that to perform not so well, but is it still better than the worst case smart match?

Before you see the benchmark, though, remember that there's almost never enough information about which technique you should use just by looking at the numbers. The context of the problem selects the best technique, not the fastest, contextless micro-benchmark. Consider a couple of cases that would select different techniques:

Now, keeping those in mind, I add to my previous program:

my %old_hash = map {$_,1} @in_middle; 

cmpthese(-5, {
    ...,
    new_hash       => sub { 
        my %h = map {$_,1} @in_middle; 
        my $count = 0;
        foreach ( @hits ) { $count++ if exists $h{$_} }
        $count;
        },
    old_hash       => sub { 
        my $count = 0;
        foreach ( @hits ) { $count++ if exists $old_hash{$_} }
        $count;
        },
    control_hash   => sub { 
        my $count = 0;
        foreach ( @hits ) { $count++ }
        $count;
        },
    }
);

Here's the plot. The colors are a bit difficult to distinguish. The lowest line there is the case where you have to create the hash any time you want to search it. That's pretty poor. The highest two (green) lines are the control for the hash (no hash actually there) and the existing hash lookup. This is a log/log plot; those two cases are faster than even the smart match control (which just calls a subroutine).

There are a few other things to note. The lines for the "random" case are a bit different. That's understandable because each benchmark (so, once per array scale run) randomly places the hit elements in the candidate array. Some runs put them a bit earlier and some a bit later, but since I only make the @random array once per run of the entire program, they move around a bit. That means that the bumps in the line aren't significant. If I tried all positions and averaged, I expect that "random" line to be the same as the "middle" line.

Now, looking at these results, I'd say that a smart-match is much faster in its worst case than the hash lookup is in its worst case. That makes sense. To create a hash, I have to visit every element of the array and also make the hash, which is a lot of copying. There's no copying with the smart match.

Here's a further case I won't examine though. When does the hash become better than the smart match? That is, when does the overhead of creating the hash spread out enough over repeated searches that the hash is the better choice?

,

Fast for small numbers of potential matches, but not faster than the hash. Hashes are really the right tool for testing set membership. Since hash access is O(log n) and smartmatch on an array is still O(n) linear scan (albeit short-circuiting, unlike grep), with larger numbers of values in the allowed matches, smartmatch gets relatively worse. Benchmark code (matching against 3 values):
#!perl
use 5.12.0;
use Benchmark qw(cmpthese);

my @hits = qw(one two three);
my @candidates = qw(one two three four five six); # 50% hit rate
my %hash;
@hash{@hits} = ();

sub count_hits_hash {
  my $count = 0;
  for (@_) {
    $count++ if exists $hash{$_};
  }
  $count;
}

sub count_hits_smartmatch {
  my $count = 0;
  for (@_) {
    $count++ when @hits;
  }
  $count;
}

say count_hits_hash(@candidates);
say count_hits_smartmatch(@candidates);

cmpthese(-5, {
    hash => sub { count_hits_hash((@candidates) x 1000) },
    smartmatch => sub { count_hits_smartmatch((@candidates) x 1000) },
  }
);
Benchmark results:
             Rate smartmatch       hash
smartmatch  404/s         --       -65%
hash       1144/s       183%         --

[Nov 13, 2019] Static code analysis module in Perl - Stack Overflow

Nov 13, 2019 | stackoverflow.com

Static code analysis module in Perl Ask Question Asked 7 years, 5 months ago Active 1 year, 7 months ago Viewed 835 times 0

DavidO ,Jun 12, 2012 at 9:13

Is there any static code analysis module in Perl except B::Lint and Perl::Critic? How effective is Module::Checkstyle?

> ,

There is a post on perlmonks.org asking if PPI can be used for static analysis. PPI is the power behind Perl::Critic, according to the reviews of this module. (I have not used it yet).

Then there is perltidy .

[Nov 12, 2019] lib-Module-Checkstyle.pm

Nov 12, 2019 | metacpan.org

Module::Checkstyle is a tool similar to checkstyle http://checkstyle.sourceforge.net for Java. It allows you to validate that your code confirms to a set of guidelines checking various things such as indentation, naming, whitespace, complexity and so forth.

Module::Checkstyle is also extensible so your organization can implement custom checks that are not provided by the standard distribution. There is a guide on how to write checks in Module::Checkstyle::Check

Module::Checkstyle is mostly used via the provided module-checkstyle tool. You probablly want to read module-checkstyle .

NAME

module-checkstyle - Check that your code keeps style

SYNOPSIS

module-checkstyle [options] [file and directories ...]

This program is the command-line interface to Module::Checkstyle .

You invoke it by supplying a list of files or directories that contain Perl code that should be checked aginst the configuration. Any problems found will be reported on standard out.

OPTIONS
-help
Print a brief help message and exits.
-man
Prints the manual page and exists.
-config
Use an alternate config file instead of ~/.module-checkstyle/config .
-all
Don't ignore common files when traversing directories. Common files are things such as blib/* t/* Makefile.PL etc.
-debug
Turn on debugging information.
-version
Display version information.

[Nov 12, 2019] Static code analysis module in Perl - Stack Overflow

Nov 12, 2019 | stackoverflow.com

Static code analysis module in Perl Ask Question Asked 7 years, 5 months ago Active 1 year, 7 months ago Viewed 835 times 0

DavidO ,Jun 12, 2012 at 9:13

Is there any static code analysis module in Perl except B::Lint and Perl::Critic? How effective is Module::Checkstyle?

> ,

There is a post on perlmonks.org asking if PPI can be used for static analysis. PPI is the power behind Perl::Critic, according to the reviews of this module. (I have not used it yet).

Then there is perltidy .

[Nov 12, 2019] lib-Module-Checkstyle.pm - metacpan.org

Nov 12, 2019 | metacpan.org

Module::Checkstyle is a tool similar to checkstyle http://checkstyle.sourceforge.net for Java. It allows you to validate that your code confirms to a set of guidelines checking various things such as indentation, naming, whitespace, complexity and so forth.

Module::Checkstyle is also extensible so your organization can implement custom checks that are not provided by the standard distribution. There is a guide on how to write checks in Module::Checkstyle::Check

Module::Checkstyle is mostly used via the provided module-checkstyle tool. You probablly want to read module-checkstyle .

NAME

module-checkstyle - Check that your code keeps style

SYNOPSIS

module-checkstyle [options] [file and directories ...]

This program is the command-line interface to Module::Checkstyle .

You invoke it by supplying a list of files or directories that contain Perl code that should be checked aginst the configuration. Any problems found will be reported on standard out.

OPTIONS
-help
Print a brief help message and exits.
-man
Prints the manual page and exists.
-config
Use an alternate config file instead of ~/.module-checkstyle/config .
-all
Don't ignore common files when traversing directories. Common files are things such as blib/* t/* Makefile.PL etc.
-debug
Turn on debugging information.
-version
Display version information.

[Nov 11, 2019] How fast is Perl's smartmatch operator when searching for a scalar in an array - Stack Overflow

Nov 11, 2019 | stackoverflow.com

[Nov 11, 2019] What are the best tools for Python static analysis

Nov 11, 2019 | www.quora.com


Christoph Neumann Answered Jun 6 2015

For web workflows check out QuantifiedCode . It's a data-driven code quality platform we've built to automate code reviews. It offers you static analysis as a service--for free.

Other tools out there are Pylint , PyFlakes , PyChecker , PEP8 , Frosted (a fork of PyFlakes) and Flake8 (a wrapper around PyFlakes and PEP8).

For more details, I compiled a tables that compares the most popular Python code analysis tools . 7.3k views · View 3 Upvoters Related Questions More Answers Below

Guillaume Bog , Python supertanker maintenance Answered Jul 9, 2012 Originally Answered: What is the best static analysis tool for Python?

I use pyflakes for code checking inside Vim and find it very useful. But still, pylint is better for pre-commit code checking. You should have two levels of code checking: errors that cannot be commited and warnings that are code-smells but can be commited. You can configure that and many other things with pylint.

Sometime you might think pylint is too picky: it may complain for something that you think is perfectly ok. Think twice about it. Very often, I found that the warning I found overly conservative some month ago was actually a very good advice.

So my answer is that pylint is reliable and robust, and I am not aware of a much better code analyzer.

pylint is very good for respecting PEP8

you can have pyflakes directly embedded in vim with this plugin:
http://www.vim.org/scripts/scrip...

Alexa Alice Answered Jul 24, 2019 · Author has 278 answers and 53.4k answer views

Spending time in the static analysis will really(really) advantage you and your group as far as time spending on discovering bugs, as far as disclosing the code to extend newcomers, regarding undertaking costs and so on. On the off chance that you invest the energy doing it forthrightly, it might appear as though you're not chipping away at highlights but rather it will return to you later on you will profit by this sooner or later.

There are a couple of interesting points on our voyage for brilliant code. In the first place, this adventure isn't one of unadulterated objectivity. There are some solid sentiments of what top-notch code resembles.

While everybody can ideally concede to the identifiers referenced over, the manner in which they get accomplished is an emotional street. The most obstinate themes generally come up when you talk about accomplishing intelligibility, upkeep, and extensibility.

To know more details: Static Analysis 342 views Related Questions More Answers Below

Dave Wade-Stein , Senior Instructor at DevelopIntelligence (2015-present) Answered Apr 15, 2018 · Author has 995 answers and 2.1m answer views

And if you're using Python 3.6+, you can add typing hints to your code and run mypy , a static typechecker over your code. (Technically, mypy will work with Python 2 code as well, but given that typing hints weren't added to Python until 3.5, you have to put the typing hints in comments which is a bit cumbersome and hard to maintain.)

[Nov 11, 2019] What are the best tools for Python static analysis - Quora

Nov 11, 2019 | www.quora.com

What are the best tools for Python static analysis?


Christoph Neumann Answered Jun 6 2015

For web workflows check out QuantifiedCode . It's a data-driven code quality platform we've built to automate code reviews. It offers you static analysis as a service--for free.

Other tools out there are Pylint , PyFlakes , PyChecker , PEP8 , Frosted (a fork of PyFlakes) and Flake8 (a wrapper around PyFlakes and PEP8).

For more details, I compiled a tables that compares the most popular Python code analysis tools . 7.3k views · View 3 Upvoters Related Questions More Answers Below

Guillaume Bog , Python supertanker maintenance Answered Jul 9, 2012 Originally Answered: What is the best static analysis tool for Python?

I use pyflakes for code checking inside Vim and find it very useful. But still, pylint is better for pre-commit code checking. You should have two levels of code checking: errors that cannot be commited and warnings that are code-smells but can be commited. You can configure that and many other things with pylint.

Sometime you might think pylint is too picky: it may complain for something that you think is perfectly ok. Think twice about it. Very often, I found that the warning I found overly conservative some month ago was actually a very good advice.

So my answer is that pylint is reliable and robust, and I am not aware of a much better code analyzer.

pylint is very good for respecting PEP8

you can have pyflakes directly embedded in vim with this plugin:
http://www.vim.org/scripts/scrip...

Alexa Alice Answered Jul 24, 2019 · Author has 278 answers and 53.4k answer views

Spending time in the static analysis will really(really) advantage you and your group as far as time spending on discovering bugs, as far as disclosing the code to extend newcomers, regarding undertaking costs and so on. On the off chance that you invest the energy doing it forthrightly, it might appear as though you're not chipping away at highlights but rather it will return to you later on you will profit by this sooner or later.

There are a couple of interesting points on our voyage for brilliant code. In the first place, this adventure isn't one of unadulterated objectivity. There are some solid sentiments of what top-notch code resembles.

While everybody can ideally concede to the identifiers referenced over, the manner in which they get accomplished is an emotional street. The most obstinate themes generally come up when you talk about accomplishing intelligibility, upkeep, and extensibility.

To know more details: Static Analysis 342 views Related Questions More Answers Below

Dave Wade-Stein , Senior Instructor at DevelopIntelligence (2015-present) Answered Apr 15, 2018 · Author has 995 answers and 2.1m answer views

And if you're using Python 3.6+, you can add typing hints to your code and run mypy , a static typechecker over your code. (Technically, mypy will work with Python 2 code as well, but given that typing hints weren't added to Python until 3.5, you have to put the typing hints in comments which is a bit cumbersome and hard to maintain.)

[Nov 10, 2019] With the rename from Perl 6 to Racu chances of mass adoption of the new language probably evaporated

Racu now needs to compete on its own merits with established languages which is extremely difficult as Ruby and Python covers the same application area
This is a positive decision for Perl5 as it slowly returns to its main niche -- the tool for advanced Unix sysadmins. Still as the decision was made rather late in language development cycle itt will negativly affect Racu future, if it has any. The main interest in the new language was because of the name -- Perl6. No this is gone.
It also split the community into Perl 5 supporters and "coming to Racu" beta addicts which is probably a good thing. But, at the same time, the loss of mindshare to Ruby and Python might accelerate.
Wikipedia already jumped the bandwagon: https://en.wikipedia.org/wiki/Raku_(programming_language)
For changes in the language see https://docs.perl6.org/language/5to6-nutshell They are not convincing
Nov 10, 2019 | news.ycombinator.com
makecheck on Oct 7, 2015 [-]
In multiple organizations I have primarily seen Perl used in a very large, complex and established code bases that also make significant use of things like reading/writing Perl data structures.

[Nov 08, 2019] Perl tricks for system administrators by Ruth Holloway Feed

Notable quotes:
"... /home/<department>/<username> ..."
Jul 27, 2016 | opensource.com

Did you know that Perl is a great programming language for system administrators? Perl is platform-independent so you can do things on different operating systems without rewriting your scripts. Scripting in Perl is quick and easy, and its portability makes your scripts amazingly useful. Here are a few examples, just to get your creative juices flowing! Renaming a bunch of files

Suppose you need to rename a whole bunch of files in a directory. In this case, we've got a directory full of .xml files, and we want to rename them all to .html . Easy-peasy!

#!/usr/bin/perl
use strict ;
use warnings ;

foreach my $file ( glob "*.xml" ) {
my $new = substr ( $file , 0 , - 3 ) . "html" ;
rename $file , $new ;
}

Then just cd to the directory where you need to make the change, and run the script. You could put this in a cron job, if you needed to run it regularly, and it is easily enhanced to accept parameters.

Speaking of accepting parameters, let's take a look at a script that does just that.

Creating a Linux user account

Programming and development

Suppose you need to regularly create Linux user accounts on your system, and the format of the username is first initial/last name, as is common in many businesses. (This is, of course, a good idea, until you get John Smith and Jane Smith working at the same company -- or want John to have two accounts, as he works part-time in two different departments. But humor me, okay?) Each user account needs to be in a group based on their department, and home directories are of the format /home/<department>/<username> . Let's take a look at a script to do that:

#!/usr/bin/env perl
use strict ;
use warnings ;

my $adduser = '/usr/sbin/adduser' ;

use Getopt :: Long qw ( GetOptions ) ;

# If the user calls the script with no parameters,
# give them help!

if ( not @ ARGV ) {
usage () ;
}

# Gather our options; if they specify any undefined option,
# they'll get sent some help!

my %opts ;
GetOptions ( \%opts ,
'fname=s' ,
'lname=s' ,
'dept=s' ,
'run' ,
) or usage () ;

# Let's validate our inputs. All three parameters are
# required, and must be alphabetic.
# You could be clever, and do this with a foreach loop,
# but let's keep it simple for now.

if ( not $opts { fname } or $opts { fname } !~ /^[a-zA-Z]+$/ ) {
usage ( "First name must be alphabetic" ) ;
}
if ( not $opts { lname } or $opts { lname } !~ /^[a-zA-Z]+$/ ) {
usage ( "Last name must be alphabetic" ) ;
}
if ( not $opts { dept } or $opts { dept } !~ /^[a-zA-Z]+$/ ) {
usage ( "Department must be alphabetic" ) ;
}

# Construct the username and home directory

my $username = lc ( substr ( $opts { fname } , 0 , 1 ) . $opts { lname }) ;
my $home = "/home/$opts{dept}/$username" ;

# Show them what we've got ready to go.

print "Name: $opts{fname} $opts{lname} \n " ;
print "Username: $username \n " ;
print "Department: $opts{dept} \n " ;
print "Home directory: $home \n\n " ;

# use qq() here, so that the quotes in the --gecos flag
# get carried into the command!

my $cmd = qq ( $adduser -- home $home -- ingroup $opts { dept } \\
-- gecos "$opts{fname} $opts{lname}" $username ) ;

print "$cmd \n " ;
if ( $opts { run }) {
system $cmd ;
} else {
print "You need to add the --run flag to actually execute \n " ;
}

sub usage {
my ( $msg ) = @_ ;
if ( $msg ) {
print "$msg \n\n " ;
}
print "Usage: $0 --fname FirstName --lname LastName --dept Department --run \n " ;
exit ;
}

As with the previous script, there are opportunities for enhancement, but something like this might be all that you need for this task.

One more, just for fun!

Change copyright text in every Perl source file in a directory tree

Now we're going to try a mass edit. Suppose you've got a directory full of code, and each file has a copyright statement somewhere in it. (Rich Bowen wrote a great article, Copyright statements proliferate inside open source code a couple of years ago that discusses the wisdom of copyright statements in open source code. It is a good read, and I recommend it highly. But again, humor me.) You want to change that text in each and every file in the directory tree. File::Find and File::Slurp are your friends!

#!/usr/bin/perl
use strict ;
use warnings ;

use File :: Find qw ( find ) ;
use File :: Slurp qw ( read_file write_file ) ;

# If the user gives a directory name, use that. Otherwise,
# use the current directory.

my $dir = $ARGV [ 0 ] || '.' ;

# File::Find::find is kind of dark-arts magic.
# You give it a reference to some code,
# and a directory to hunt in, and it will
# execute that code on every file in the
# directory, and all subdirectories. In this
# case, \&change_file is the reference
# to our code, a subroutine. You could, if
# what you wanted to do was really short,
# include it in a { } block instead. But doing
# it this way is nice and readable.

find ( \&change_file , $dir ) ;

sub change_file {
my $name = $_ ;

# If the file is a directory, symlink, or other
# non-regular file, don't do anything

if ( not - f $name ) {
return ;
}
# If it's not Perl, don't do anything.

if ( substr ( $name , - 3 ) ne ".pl" ) {
return ;
}
print "$name \n " ;

# Gobble up the file, complete with carriage
# returns and everything.
# Be wary of this if you have very large files
# on a system with limited memory!

my $data = read_file ( $name ) ;

# Use a regex to make the change. If the string appears
# more than once, this will change it everywhere!

$data =~ s/Copyright Old/Copyright New/g ;

# Let's not ruin our original files

my $backup = "$name.bak" ;
rename $name , $backup ;
write_file ( $name , $data ) ;

return ;
}

Because of Perl's portability, you could use this script on a Windows system as well as a Linux system -- it Just Works because of the underlying Perl interpreter code. In our create-an-account code above, that one is not portable, but is Linux-specific because it uses Linux commands such as adduser .

In my experience, I've found it useful to have a Git repository of these things somewhere that I can clone on each new system I'm working with. Over time, you'll think of changes to make to the code to enhance the capabilities, or you'll add new scripts, and Git can help you make sure that all your tools and tricks are available on all your systems.

I hope these little scripts have given you some ideas how you can use Perl to make your system administration life a little easier. In addition to these longer scripts, take a look at a fantastic list of Perl one-liners, and links to other Perl magic assembled by Mischa Peterson.

[Oct 22, 2019] Is there an advantage to using Bash over Perl or Python?

Oct 22, 2019 | stackoverflow.com

Ask Question Asked 8 years, 5 months ago Active 8 years, 5 months ago Viewed 19k times 23 10


> ,May 2, 2011 at 18:58

Hey I've been using Linux for a while and thought it was time to finally dive into shell scripting.

The problem is I've failed to find any significant advantage of using Bash over something like Perl or Python. Are there any performance or power differences between the two? I'd figure Python/Perl would be more well suited as far as power and efficiency goes.

Sebastian ,May 2, 2011 at 15:21

Two advantages come to mind:

By the way, I usually have some python calls in my bash scripts (e.g. for plotting). Use whatever is best for the task!

Mario Peshev ,May 2, 2011 at 15:16

Perl scripts are usually (if not 100% of the times) faster than bash.

A discussion on that: Perl vs Bash

reinierpost ,May 7, 2011 at 12:16

bash isn't a language so much as a command interpreter that's been hacked to death to allow for things that make it look like a scripting language. It's great for the simplest 1-5 line one-off tasks, but things that are dead simple in Perl or Python like array manipulation are horribly ugly in bash. I also find that bash tends not to pass two critical rules of thumb:
  1. The 6-month rule, which says you should be able to easily discern the purpose and basic mechanics of a script you wrote but haven't looked at in 6 months.
  2. The 'WTF per minute' rule. Everyone has their limit, and mine is pretty small. Once I get to 3 WTFs/min, I'm looking elsewhere.

As for 'shelling out' in scripting languages like Perl and Python, I find that I almost never need to do this, fwiw (disclaimer: I code almost 100% in Python). The Python os and shutil modules have most of what I need most of the time, and there are built-in modules for handling tarfiles, gzip files, zip files, etc. There's a glob module, an fnmatch module... there's a lot of stuff there. If you come across something you need to parallelize, then indent your code a level, put it in a 'run()' method, put that in a class that extends either threading.Thread or multiprocessing.Process, instantiate as many of those as you want, calling 'start()' on each one. Less than 5 minutes to get parallel execution generally.

Best of luck. Hope this helps.

daotoad ,May 2, 2011 at 17:40

For big projects use a language like Perl.

There are a few things you can only do in bash (for example, alter the calling environment (when a script is sourced rather than run). Also, shell scripting is commonplace. It is worthwhile to learn the basics and learn your way around the available docs.

Plus there are times when knowing a shell well can save your bacon (on a fork-bombed system where you can't start any new processes, or if /usr/bin and or /usr/local/bin fail to mount).

Sebastian ,May 3, 2011 at 8:47

The advantage is that it's right there. Unless you use Python (or Perl) as your shell, writing a script to do a simple loop is a bunch of extra work.

For short, simple scripts that call other programs, I'll use Bash. If I want to keep the output, odds are good that I'll trade up to Python.

For example:

for file in *; do process $file ; done

where process is a program I want to run on each file, or...

while true; do program_with_a_tendency_to_fail ; done

Doing either of those in Python or Perl is overkill.

For actually writing a program that I expect to maintain and use over time, Bash is rarely the right tool for the job. Particularly since most modern Unices come with both Perl and Python.

tchrist ,May 4, 2011 at 11:01

The most important advantage of POSIX shell scripts over Python or Perl scripts is that a POSIX shell is available on virtually every Unix machine. (There are also a few tasks shell scripts happen to be slightly more convenient for, but that's not a major issue.) If the portability is not an issue for you, I don't see much need to learn shell scripting.

tchrist ,May 3, 2011 at 23:50

If you want to execute programs installed on the machine, nothing beats bash. You can always make a system call from Perl or Python, but I find it to be a hassle to read return values, etc.

And since you know it will work pretty much anywhere throughout all of of time...

Alexandr Ciornii ,May 3, 2011 at 8:26

The advantage of shell scripting is that it's globally present on *ix boxes, and has a relatively stable core set of features you can rely on to run everywhere. With Perl and Python you have to worry about whether they're available and if so what version, as there have been significant syntactical incompatibilities throughout their lifespans. (Especially if you include Python 3 and Perl 6.)

The disadvantage of shell scripting is everything else. Shell scripting languages are typically lacking in expressiveness, functionality and performance. And hacking command lines together from strings in a language without strong string processing features and libraries, to ensure the escaping is correct, invites security problems. Unless there's a compelling compatibility reason you need to go with shell, I would personally plump for a scripting language every time.

[Oct 22, 2019] Larry Wall Approves Re-Naming Perl 6 To Raku

Oct 22, 2019 | developers.slashdot.org

(github.com) 100 hondo77 notes that Larry Wall has given his approval to the re-naming of Perl 6.

In the "Path to Raku" pull request, Larry Wall indicated his approval, leaving this comment: I am in favor of this change, because it reflects an ancient wisdom :

"No one sews a patch of unshrunk cloth on an old garment, for the patch will pull away from the garment, making the tear worse. Neither do people pour new wine into old wineskins. If they do, the skins will burst; the wine will run out and the wineskins will be ruined. No, they pour new wine into new wineskins, and both are preserved."

"Perl 6 will become Raku, assuming the four people who haven't yet approved the pull request give their okay," reports the Register, adding that Perl 5 will then become simply Perl .

Dozens of comments on that pull request have now already been marked as "outdated," and while a few contributors have made a point of abstaining from the approval process, reviewer Alex Daniel notes that "this pull request will be merged on October 14th if nobody in the list rejects it or requests more changes."

[Oct 21, 2019] Differences between Perl and PHP [closed]

Notable quotes:
"... Perl has native regular expression support, ..."
"... Perl has quite a few more operators , including matching ..."
"... In PHP, new is an operator. In Perl, it's the conventional name of an object creation subroutine defined in packages, nothing special as far as the language is concerned. ..."
"... Perl logical operators return their arguments, while they return booleans in PHP. ..."
"... Perl gives access to the symbol table ..."
"... Note that "references" has a different meaning in PHP and Perl. In PHP, references are symbol table aliases. In Perl, references are smart pointers. ..."
"... Perl has different types for integer-indexed collections (arrays) and string indexed collections (hashes). In PHP, they're the same type: an associative array/ordered map ..."
"... Perl arrays aren't sparse ..."
"... Perl supports hash and array slices natively, ..."
Nov 23, 2013 | stackoverflow.com

jholster ,Nov 23, 2013 at 21:20

I'm planning to learn Perl 5 and as I have only used PHP until now, I wanted to know a bit about how the languages differ from each other.

As PHP started out as a set of "Perl hacks" it has obviously cloned some of Perls features.

hobbs ,Jan 17, 2013 at 8:36

Perl and PHP are more different than alike. Let's consider Perl 5, since Perl 6 is still under development. Some differences, grouped roughly by subject:

PHP was inspired by Perl the same way Phantom of the Paradise was inspired by Phantom of the Opera , or Strange Brew was inspired by Hamlet . It's best to put the behavior specifics of PHP out of your mind when learning Perl, else you'll get tripped up.

My brain hurts now, so I'm going to stop.

Your Common Sense ,Mar 29, 2010 at 2:19

When PHP came to the scene, everyone were impressed with main differences from Perl:
  1. Input variables already in the global scope, no boring parsing.
  2. HTML embedding. Just <?php ... ?> anywhere. No boring templates.
  3. On-screen error messages. No boring error log peeks.
  4. Easy to learn. No boring book reading.

As the time passed, everyone learned that they were not a benefit, hehe...

Quentin ,Jan 15, 2016 at 3:27

I've noticed that most PHP vs. Perl pages seem to be of the

PHP is better than Perl because <insert lame reason here>

ilk, and rarely make reasonable comparisons.

Syntax-wise, you will find PHP is often easier to understand than Perl, particularly when you have little experience. For example, trimming a string of leading and trailing whitespace in PHP is simply

$string = trim($string);

In Perl it is the somewhat more cryptic

$string =~ s/^\s+//;
$string =~ s/\s+$//;

(I believe this is slightly more efficient than a single line capture and replace, and also a little more understandable.) However, even though PHP is often more English-like, it sometimes still shows its roots as a wrapper for low level C, for example, strpbrk and strspn are probably rarely used, because most PHP dabblers write their own equivalent functions for anything too esoteric, rather than spending time exploring the manual. I also wonder about programmers for whom English is a second language, as everybody is on equal footing with things such as Perl, having to learn it from scratch.

I have already mentioned the manual. PHP has a fine online manual, and unfortunately it needs it. I still refer to it from time to time for things that should be simple, such as order of parameters or function naming convention. With Perl, you will probably find you are referring to the manual a lot as you get started and then one day you will have an a-ha moment and never need it again. Well, at least not until you're more advanced and realize that not only is there more than one way, there is probably a better way, somebody else has probably already done it that better way, and perhaps you should just visit CPAN.

Perl does have a lot more options and ways to express things. This is not necessarily a good thing, although it allows code to be more readable if used wisely and at least one of the ways you are likely to be familiar with. There are certain styles and idioms that you will find yourself falling into, and I can heartily recommend reading Perl Best Practices (sooner rather than later), along with Perl Cookbook, Second Edition to get up to speed on solving common problems.

I believe the reason Perl is used less often in shared hosting environments is that historically the perceived slowness of CGI and hosts' unwillingness to install mod_perl due to security and configuration issues has made PHP a more attractive option. The cycle then continued, more people learned to use PHP because more hosts offered it, and more hosts offered it because that's what people wanted to use. The speed differences and security issues are rendered moot by FastCGI these days, and in most cases PHP is run out of FastCGI as well, rather than leaving it in the core of the web server.

Whether or not this is the case or there are other reasons, PHP became popular and a myriad of applications have been written in it. For the majority of people who just want an entry-level website with a simple blog or photo gallery, PHP is all they need so that's what the hosts promote. There should be nothing stopping you from using Perl (or anything else you choose) if you want.

At an enterprise level, I doubt you would find too much PHP in production (and please, no-one point at Facebook as a counter-example, I said enterprise level).

Leon Timmermans ,Mar 28, 2010 at 22:15

Perl is used plenty for websites, no less than Python and Ruby for example. That said, PHP is used way more often than any of those. I think the most important factors in that are PHP's ease of deployment and the ease to start with it.

The differences in syntax are too many to sum up here, but generally it is true that it has more ways to express yourself (this is know as TIMTWOTDI, There Is More Than One Way To Do It).

Brad Gilbert ,Mar 29, 2010 at 4:04

My favorite thing about Perl is the way it handles arrays/lists. Here's an example of how you would make and use a Perl function (or "subroutine"), which makes use of this for arguments:
sub multiply
{
    my ($arg1, $arg2) = @_; # @_ is the array of arguments
    return $arg1 * $arg2;
}

In PHP you could do a similar thing with list() , but it's not quite the same; in Perl lists and arrays are actually treated the same (usually). You can also do things like:

$week_day_name = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")[$week_day_index];

And another difference that you MUST know about, is numerical/string comparison operators. In Perl, if you use < , > , == , != , <=> , and so on, Perl converts both operands to numbers. If you want to convert as strings instead, you have to use lt , gt , eq , ne , cmp (the respective equivalents of the operators listed previously). Examples where this will really get you:

if ("a" == "b") { ... } # This is true.
if ("a" == 0) { ... } # This is also true, for the same reason.

Sorin Postelnicu, Aug 5, 2015 at 15:44

I do not need add anything to outis's fantastic answer, i want only show the answer for you question:

Why is Perl not used for dynamic websites very often anymore? What made PHP gain more popularity than it?

Please check first some "Job Trends" sites - and you can make the judgement alone.

as you can see, perl is still a leader - but preferable for real applications not for toys. :)

[Oct 13, 2019] How to eliminate a value in the middle of an array in Perl by Gabor Szabo

Gabor Szabo is an expert in Perl who originally wrote Padre Perl Padre http://padre.perlide.org (abandonware since 2013). The last that was available was Ubuntu 10.10.
Notable quotes:
"... This code will set element 3 (the 4th element of the array) to undef , but will NOT change the size of the array: ..."
Oct 13, 2019 | perlmaven.com
In response to an earlier article about undef one of the readers asked me:

How do you eliminate a value in the middle of an array in Perl?

I am not sure if undef and eliminating values from an array are related, though I guess, if we see having a value of undef as being "empty", then I can understand the connection. In general though, setting something to be undef and deleting something is not the same.

Are you serious about Perl? Check out my Beginner Perl Maven book .
I have written it for you!

Let's see first how we can set an element of an array to be undef and then how we can delete an element from an array.

We start with the following code:

  1. use Data :: Dumper qw ( Dumper );
  2. my @dwarfs = qw ( Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
  3. print Dumper \@dwarfs ;

When printed using Data::Dumper we get the following output:

$VAR1 = [
          'Doc',
          'Grumpy',
          'Happy',
          'Sleepy',
          'Sneezy',
          'Dopey',
          'Bashful'
        ];
Set an element to undef

Using the return value of the undef() function:

  1. use Data :: Dumper qw ( Dumper );
  2. my @dwarfs = qw ( Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
  3. $dwarfs [ 3 ] = undef ;
  4. print Dumper \@dwarfs ;

This code will set element 3 (the 4th element of the array) to undef , but will NOT change the size of the array:

$VAR1 = [
          'Doc',
          'Grumpy',
          'Happy',
          undef,
          'Sneezy',
          'Dopey',
          'Bashful'
        ];

Using the undef() function directly on an element of an array yields similar results:

  1. use Data :: Dumper qw ( Dumper );
  2. my @dwarfs = qw ( Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
  3. undef $dwarfs [ 3 ];
  4. print Dumper \@dwarfs ;

So for our purposes $dwarfs[3] = undef; and undef $dwarfs[3]; do the same thing. They both can set a value to be undef .

Removing an element from the array using splice

The splice function can totally eliminate the value from the array:

  1. use Data :: Dumper qw ( Dumper );
  2. my @dwarfs = qw ( Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
  3. splice @dwarfs,3,1;
  4. print Dumper \@dwarfs ;
$VAR1 = [
          'Doc',
          'Grumpy',
          'Happy',
          'Sneezy',
          'Dopey',
          'Bashful'
        ];

As you can see, in this case the array became one element shorter as we have removed one of the elements from the middle of the array.

This is how you can delete an element from an array .

[Oct 13, 2019] What are Donald Knuth's main original contributions to computer science - Quora

Oct 13, 2019 | www.quora.com

Radu Grigore , argued rigor Answered Apr 22 2012 I think some of the main original contributions to Computer Science are the following:

He also did some work in mathematics. If I remember correctly, I saw him in a video saying that the article he is most proud of is The Birth of the Giant Component . Mark VandeWettering , I have a lab coat, trust me! Answered Jan 10, 2014 · Author has 7.2k answers and 23.3m answer views Knuth won the Turing Award in 1974 for his contributions to the analysis of algorithms I'd submit that his "expository" work in the form of The Art of Programming go well beyond simple exposition, and brought a rigor and precision to the analysis of algorithms which was (and probably still is) unparalleled in term of thoroughness and scope. There is more knowledge in the margins of The Art of Programming than there is in most programming courses. 1.2k views · View 7 Upvoters Eugene Miya Eugene Miya , Ex-Journal Editor, parallelism DB, committees and conferences, etc. Answered Sep 9, 2014 · Author has 11.2k answers and 7.9m answer views Everyone cites and overcites TAOCP.

Start collecting Selected Papers (in|on) ... He has 8 volumes. If you need the titles consider Amazon: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more or Barnes &Noble: Books, Textbooks, eBooks, Toys, Games & More for their ToC.

[Oct 13, 2019] 7 of the most useful Perl command line options by Gabor Szabo

Oct 13, 2019 | perlmaven.com

-e execute code on the command line

For one-off tasks it can be very useful to be able to run a piece of Perl code without creating a file. The code itself needs to be between quotes. Due to differences between the Unix/Linux shell and the MS Windows Command prompt we need to use different quotes around our code.

On Unix/Linux systsem (including Mac OSX) it is recommended to put our code in single quotes as in the following example:

$ perl -e 'print qq{Hello World\n}'

Hello World

On MS Windows we must use double quotes around our code.

$ perl -e "print qq{Hello World\n}"

Hello World

Internally, it is probably the best to use q and qq instead of single-quote and double-quote, respectively. That might help reduce the confusion caused by the behavior of the shell and command prompt.

-E execute code on the command line with all the latest features enabled

Since version 5.10 of Perl has been released, Perl includes some additional keywords (called features) in the language. For improved backward compatibility these keywords are only enabled if the user explicitly ask for them with use feature ... . For example by writing use feature qw(say); , or by declaring a minimal version of Perl with use 5.010; .

On the command line we can achieve the same by using -E instead of -e . It will turn on all the features of the version of Perl we are currently running.

For me the most important of all these features, at least in one-liners is the say keyword introduced in perl 5.10 . It is just print with a trailing newline added. Nothing fancy, but makes the one-liners even shorter.

The above examples would look like these:

Unix/Linux:

$ perl -E 'say q{Hello World}'

Hello World

MS Windows:

$ perl -E "say q{Hello World}"

Hello World

You can notice the change from qq to q . As we don't need to include a newline \n in our strings we could switch from qq to q .

-n wrap the -e/-E code in a while loop

If we provide the -n command line option it will wrap our code provided using either the -e or the -E options in a while with a diamond operator .

So

perl -n -E 'say if /code/' file.txt

is the same as

while (<>) {
    say if /code/;
}

That will go over all the lines of all the files provided on the command line (in this case it is file.txt) and print out every line that matches the /code/ regex.

-p is like -n with print $_

The -p option is very similar to the -n flag, but it also prints the content of $_ at the end of each iteration.

So we could write:

perl -p -E 's/code/foobar/' file.txt

which would become

while (<>) {
    s/code/foobar/
    print;
}

That will print the result to the screen.

-i for in-place editing

The most common use of -p is together with the -i option that provides "in-place editing". It means that instead of printing to the screen, all the output generated by our one-liner will be written back to the same file it was taken from.

So this one-liner will replace the first appearance of the string "code" by "foobar" in every line of the file "file.txt".

perl -i -p -E 's/code/foobar/' file.txt

[Oct 09, 2019] Static and state variables in Perl

Oct 09, 2019 | perlmaven.com

Prev Next In most of the cases we either want a variable to be accessible only from inside a small scope, inside a function or even inside a loop. These variables get created when we enter the function (or the scope created by a a block) and destroyed when we leave the scope.

In some cases, especially when we don't want to pay attention to our code, we want variables to be global, to be accessible from anywhere in our script and be destroyed only when the script ends. In General having such global variables is not a good practice.

In some cases we want a variable to stay alive between function calls, but still to be private to that function. We want it to retain its value between calls.

Are you serious about Perl? Check out my Beginner Perl Maven book .
I have written it for you!

In the C programming language one can designate a variable to be a static variable . This means it gets initialized only once and it sticks around retaining its old value between function calls.

In Perl, the same can be achieved using the state variable which is available starting from version 5.10, but there is a construct that will work in every version of Perl 5. In a way it is even more powerful.

Let's create a counter as an example:

state variable
  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. sub count {
  5. state $counter = 0 ;
  6. $counter ++;
  7. return $counter ;
  8. }
  9. say count ();
  10. say count ();
  11. say count ();
  12. #say $counter;

In this example, instead of using my to declare the internal variable , we used the state keyword.

$counter is initialized to 0 only once, the first time we call counter() . In subsequent calls, the line state $counter = 0; does not get executed and $counter has the same value as it had when we left the function the last time.

Thus the output will be:

1
2
3

If we removed the # from last line, it would generate a Global symbol "$counter" requires explicit package name at ... line ... error when trying to compile the script. This just shows that the variable $counter is not accessible outside the function.

state is executed in the first call

Check out this strange example:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. sub count {
  5. state $counter = say "world" ;
  6. $counter ++;
  7. return $counter ;
  8. }
  9. say "hello" ;
  10. say count ();
  11. say count ();
  12. say count ();

This will print out

hello
world
2
3
4

showing that the state $counter = say "world"; line only gets executed once. In the first call to count() say , which was also added in version 5.10 , will return 1 upon success.

static variables in the "traditional" way
  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. {
  5. my $counter = 0 ;
  6. sub count {
  7. $counter ++;
  8. return $counter ;
  9. }
  10. }
  11. say count ();
  12. say count ();
  13. say count ();

This provides the same result as the above version using state , except that this could work in older versions of perl as well. (Especially if I did not want to use the say keyword, that was also introduced in 5.10.)

This version works because functions declarations are global in perl - so count() is accessible in the main body of the script even though it was declared inside a block. On the other hand the variable $counter is not accessible from the outside world because it was declared inside the block. Lastly, but probably most importantly, it does not get destroyed when we leave the count() function (or when the execution is outside the block), because the existing count() function still references it.

Thus $count is effectively a static variable.

First assignment time
  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. say "hi" ;
  5. {
  6. my $counter = say "world" ;
  7. sub count {
  8. $counter ++;
  9. return $counter ;
  10. }
  11. }
  12. say "hello" ;
  13. say count ();
  14. say count ();
  15. say count ();
hi
world
hello
2
3
4

This shows that in this case too, the declaration and the initial assignment my $counter = say "world"; happens only once, but we can also see that the assignment happens before the first call to count() as if the my $counter = say "world"; statement was part of the control flow of the code outside of the block.

Shared static variable

This "traditional" or "home made" static variable has an extra feature. Because it does not belong to the the count() subroutine, but to the block surrounding it, we can declare more than one functions in that block and we can share this static variable between two or even more functions.

For example we could add a reset_counter() function:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. {
  5. my $counter = 0 ;
  6. sub count {
  7. $counter ++;
  8. return $counter ;
  9. }
  10. sub reset_counter {
  11. $counter = 0 ;
  12. }
  13. }
  14. say count ();
  15. say count ();
  16. say count ();
  17. reset_counter ();
  18. say count ();
  19. say count ();
1
2
3
1
2

Now both functions can access the $counter variable, but still nothing outside the enclosing block can access it.

Static arrays and hashes

As of now, you cannot use the state declaration in list context. This means you cannot write state @y = (1, 1); . This limitation could be overcome by some extra coding. For example in this implementation of the Fibonacci series, we checked if the array is empty and set the default values:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. sub fib {
  5. state @y ;
  6. @y = ( 1 , 1 ) if not @y ; # workaround initialization
  7. push @y , $y [ 0 ]+ $y [ 1 ];
  8. return shift @y ;
  9. }
  10. say fib ();
  11. say fib ();
  12. say fib ();
  13. say fib ();
  14. say fib ();

Alternatively we could use the "old-style" static variable with the enclosing block.

Here is the example generating the Fibonacci series:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. {
  5. my @y = ( 1 , 1 );
  6. sub fib {
  7. push @y , $y [ 0 ]+ $y [ 1 ];
  8. return shift @y ;
  9. }
  10. }
  11. say fib ();
  12. say fib ();
  13. say fib ();
  14. say fib ();
  15. say fib ();

[Oct 09, 2019] use vars vs ours

Oct 09, 2019 | perlmaven.com

use vars

The problem is that use strict is complaining that there is a variable $x which is not declared with my and that it does not know about it. So we need a way to tell strict that it is ok. We know about the $x variable and we want to use it, but we want it to be a package variable. We don't want to declare it using my and we don't want to always prefix it with the package name.

With use vars ('$x') we can achieve that:

  1. use strict ;
  2. package VeryLongName ;
  3. use vars ( '$x' );
  4. $x = 23 ;
  5. print "VeryLongName: $x\n" ;

This works, but the documentation of vars tells us that the functionality provided by this pragma has been superseded by "our" declarations .

So how does our work?

our
  1. use strict ;
  2. package VeryLongName ;
  3. our $x = 23 ;
  4. print "VeryLongName: $x\n" ;
Caveat

The our declaration itself is lexically scoped, meaning it is limited by the file or by enclosing curly braces. In the next example we don't have curly braces and thus the declaration our $x = 23; will be intact even after switching namespaces. This can lead to very unpleasant situations. My recommendation is to avoid using our (you almost always need to use my anyway) and to put every package in its own file.

  1. use strict ;
  2. package VeryLongName ;
  3. our $x = 23 ;
  4. print "VeryLongName: $x\n" ; # VeryLongName: 23
  5. package main ;
  6. print "$x\n" ; # 23

[Oct 09, 2019] scope - What is the difference between my and our in Perl - Stack Overflow

Oct 09, 2019 | stackoverflow.com

Asked 10 years, 5 months ago Active 3 years, 1 month ago Viewed 107k times 180 56


Nathan Fellman ,May 10, 2009 at 10:24

I know what my is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does our do? How does our differ from my ?

Nathan Fellman ,Nov 20, 2016 at 1:15

Great question: How does our differ from my and what does our do?

In Summary:

Available since Perl 5, my is a way to declare:


On the other hand, our variables are:


Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars , which was only file-scoped, and not lexically scoped as is our .

For example, the formal, qualified name for variable $x inside package main is $main::x . Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars" . The scope might be one, or two, or more packages, or one small block.

Georg ,Oct 1, 2016 at 6:41

The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:

my variables are lexically scoped within a single block defined by {} or within the same file if not in {} s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.

our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.

Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.

Nathan Fellman ,Nov 20, 2015 at 18:46

An example:
use strict;

for (1 .. 2){
    # Both variables are lexically scoped to the block.
    our ($o);  # Belongs to 'main' package.
    my  ($m);  # Does not belong to a package.

    # The variables differ with respect to newness.
    $o ++;
    $m ++;
    print __PACKAGE__, " >> o=$o m=$m\n";  # $m is always 1.

    # The package has changed, but we still have direct,
    # unqualified access to both variables, because the
    # lexical scope has not changed.
    package Fubb;
    print __PACKAGE__, " >> o=$o m=$m\n";
}

# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n";  # 2
print __PACKAGE__, " >> main::m=$main::m\n";  # Undefined.

# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";

# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
    use vars qw($uv);
    $uv ++;
}

# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";

# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";

daotoad ,May 10, 2009 at 16:37

Coping with Scoping is a good overview of Perl scoping rules. It's old enough that our is not discussed in the body of the text. It is addressed in the Notes section at the end.

The article talks about package variables and dynamic scope and how that differs from lexical variables and lexical scope.

Chas. Owens ,Oct 7, 2013 at 14:02

my is used for local variables, where as our is used for global variables. More reading over Variable Scoping in Perl: the basics .

ruffin ,Feb 10, 2015 at 19:47

It's an old question, but I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:

1. definition or declaration?

local $var = 42; 
print "var: $var\n";

The output is var: 42 . However we couldn't tell if local $var = 42; is a definition or declaration. But how about this:

use strict;
use warnings;

local $var = 42;
print "var: $var\n";

The second program will throw an error:

Global symbol "$var" requires explicit package name.

$var is not defined, which means local $var; is just a declaration! Before using local to declare a variable, make sure that it is defined as a global variable previously.

But why this won't fail?

use strict;
use warnings;

local $a = 42;
print "var: $a\n";

The output is: var: 42 .

That's because $a , as well as $b , is a global variable pre-defined in Perl. Remember the sort function?

2. lexical or global?

I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: just corresponds to auto and external variables in C. But there're small differences:

In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:

int global;

int main(void) {
    int local;
}

While in Perl, things are subtle:

sub main {
    $var = 42;
}

&main;

print "var: $var\n";

The output is var: 42 , $var is a global variable even it's defined in a function block! Actually in Perl, any variable is declared as global by default.

The lesson is to always add use strict; use warnings; at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.

Ólafur Waage ,May 10, 2009 at 10:25

The perldoc has a good definition of our.

Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.

Cosmicnet ,Nov 22, 2014 at 13:57

This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl

our $foo = "BAR";

print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";

Output:

BAR
BAZ

This won't work if you change 'our' to 'my'.

Okuma.Scott ,Sep 6, 2014 at 20:13

print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";

package Changed;

{
        my $test = 10;
        my $test1 = 11;
        print "trying to print local vars from a closed block: $test, $test1\n";
}

&Check_global;

sub Check_global {
        print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package:     $test\n";
print "trying to print local var outside the block $test1\n";

Will Output this:

package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block

In case using "use strict" will get this failure while attempting to run the script:

Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.

Nathan Fellman ,Nov 5, 2015 at 14:03

Just try to use the following program :
#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;


print "$a \n";
print "$b \n";
}

package b;

#my $b = 200;
#our $a = 20 ;

print "in package b value of  my b $a::b \n";
print "in package b value of our a  $a::a \n";

Nathan Fellman ,May 16, 2013 at 11:07

#!/usr/bin/perl -l

use strict;

# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'

our $lol = eval {$lol} || 'lol' ;

print $lol;

Evgeniy ,Jan 27, 2016 at 4:57

Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.

On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.

The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.

Sources:

[Oct 09, 2019] Perl Import Package in different Namespace

Oct 09, 2019 | stackoverflow.com

Perl Import Package in different Namespace Ask Question Asked 1 year ago Active 7 months ago Viewed 150 times We're doing things differently. View all 8 job openings! 2


choroba ,Sep 28, 2018 at 22:17

is it possible to import ( use ) a perl module within a different namespace?

Let's say I have a Module A (XS Module with no methods Exported @EXPORT is empty) and I have no way of changing the module.

This Module has a Method A::open

currently I can use that Module in my main program (package main) by calling A::open I would like to have that module inside my package main so that I can directly call open

I tried to manually push every key of %A:: into %main:: however that did not work as expected.

The only way that I know to achieve what I want is by using package A; inside my main program, effectively changing the package of my program from main to A . Im not satisfied with this. I would really like to keep my program inside package main.

Is there any way to achieve this and still keep my program in package main?

Offtopic: Yes I know usually you would not want to import everything into your namespace but this module is used by us extensively and we don't want to type A:: (well the actual module name is way longer which isn't making the situation better)in front of hundreds or thousands of calls

Grinnz ,Oct 1, 2018 at 6:26

This is one of those "impossible" situations, where the clear solution -- to rework that module -- is off limits.

But, you can alias that package's subs names, from its symbol table, to the same names in main . Worse than being rude, this comes with a glitch: it catches all names that that package itself imported in any way. However, since this package is a fixed quantity it stands to reason that you can establish that list (and even hard-code it). It is just this one time, right?

main

use warnings;
use strict;
use feature 'say';

use OffLimits;

GET_SUBS: {
    # The list of names to be excluded
    my $re_exclude = qr/^(?:BEGIN|import)$/;  # ...
    my @subs = grep { !/$re_exclude/ } sort keys %OffLimits::;
    no strict 'refs';
    for my $sub_name (@subs) {
        *{ $sub_name } = \&{ 'OffLimits::' . $sub_name };
    }   
};

my $name = name('name() called from ' . __PACKAGE__);
my $id   = id('id() called from ' . __PACKAGE__);

say "name() returned: $name";
say "id()   returned: $id";

with OffLimits.pm

package OffLimits;    
use warnings;
use strict;

sub name { return "In " .  __PACKAGE__ . ": @_" }
sub id   { return "In " .  __PACKAGE__ . ": @_" }

1;

It prints

name() returned: In OffLimits: name() called from  main
id()   returned: In OffLimits: id() called from  main

You may need that code in a BEGIN block, depending on other details.

Another option is of course to hard-code the subs to be "exported" (in @subs ). Given that the module is in practice immutable this option is reasonable and more reliable.


This can also be wrapped in a module, so that you have the normal, selective, importing.

WrapOffLimits.pm

package WrapOffLimits;
use warnings;
use strict;

use OffLimits;

use Exporter qw(import);

our @sub_names;
our @EXPORT_OK   = @sub_names;
our %EXPORT_TAGS = (all => \@sub_names);

BEGIN { 
    # Or supply a hard-coded list of all module's subs in @sub_names
    my $re_exclude = qr/^(?:BEGIN|import)$/;  # ...
    @sub_names = grep { !/$re_exclude/ } sort keys %OffLimits::;

    no strict 'refs';
    for my $sub_name (@sub_names) {
        *{ $sub_name } = \&{ 'OffLimits::' . $sub_name };
    }   
};
1;

and now in the caller you can import either only some subs

use WrapOffLimits qw(name);

or all

use WrapOffLimits qw(:all);

with otherwise the same main as above for a test.

The module name is hard-coded, which should be OK as this is meant only for that module.


The following is added mostly for completeness.

One can pass the module name to the wrapper by writing one's own import sub, which is what gets used then. The import list can be passed as well, at the expense of an awkward interface of the use statement.

It goes along the lines of

package WrapModule;
use warnings;
use strict;

use OffLimits;

use Exporter qw();  # will need our own import 

our ($mod_name, @sub_names);

our @EXPORT_OK   = @sub_names;
our %EXPORT_TAGS = (all => \@sub_names);

sub import {
    my $mod_name = splice @_, 1, 1;  # remove mod name from @_ for goto

    my $re_exclude = qr/^(?:BEGIN|import)$/;  # etc

    no strict 'refs';
    @sub_names = grep { !/$re_exclude/ } sort keys %{ $mod_name . '::'};    
    for my $sub_name (@sub_names) {    
        *{ $sub_name } = \&{ $mod_name . '::' . $sub_name };
    }   

    push @EXPORT_OK, @sub_names;

    goto &Exporter::import;
}
1;

what can be used as

use WrapModule qw(OffLimits name id);  # or (OffLimits :all)

or, with the list broken-up so to remind the user of the unusual interface

use WrapModule 'OffLimits', qw(name id);

When used with the main above this prints the same output.

The use statement ends up using the import sub defined in the module, which exports symbols by writing to the caller's symbol table. (If no import sub is written then the Exporter 's import method is nicely used, which is how this is normally done.)

This way we are able to unpack the arguments and have the module name supplied at use invocation. With the import list supplied as well now we have to push manually to @EXPORT_OK since this can't be in the BEGIN phase. In the end the sub is replaced by Exporter::import via the (good form of) goto , to complete the job.

Simerax ,Sep 30, 2018 at 10:19

You can forcibly "import" a function into main using glob assignment to alias the subroutine (and you want to do it in BEGIN so it happens at compile time, before calls to that subroutine are parsed later in the file):
use strict;
use warnings;
use Other::Module;

BEGIN { *open = \&Other::Module::open }

However, another problem you might have here is that open is a builtin function, which may cause some problems . You can add use subs 'open'; to indicate that you want to override the built-in function in this case, since you aren't using an actual import function to do so.

Grinnz ,Sep 30, 2018 at 17:33

Here is what I now came up with. Yes this is hacky and yes I also feel like I opened pandoras box with this. However at least a small dummy program ran perfectly fine.

I renamed the module in my code again. In my original post I used the example A::open actually this module does not contain any method/variable reserved by the perl core. This is why I blindly import everything here.

BEGIN {
    # using the caller to determine the parent. Usually this is main but maybe we want it somewhere else in some cases
    my ($parent_package) = caller;

    package A;

    foreach (keys(%A::)) {
        if (defined $$_) {
            eval '*'.$parent_package.'::'.$_.' = \$A::'.$_;
        }
        elsif (%$_) {
            eval '*'.$parent_package.'::'.$_.' = \%A::'.$_;
        }
        elsif (@$_) {
            eval '*'.$parent_package.'::'.$_.' = \@A::'.$_;
        }
        else {
            eval '*'.$parent_package.'::'.$_.' = \&A::'.$_;
        }
    }
}

[Oct 09, 2019] oop - Perl Importing Variables From Calling Module

Oct 09, 2019 | stackoverflow.com

Perl Importing Variables From Calling Module Ask Question Asked 9 years, 1 month ago Active 9 years, 1 month ago Viewed 4k times 0 1


Russell C. ,Aug 31, 2010 at 20:31

I have a Perl module (Module.pm) that initializes a number of variables, some of which I'd like to import ($VAR2, $VAR3) into additional submodules that it might load during execution.

The way I'm currently setting up Module.pm is as follows:

package Module;

use warnings;
use strict;

use vars qw($SUBMODULES $VAR1 $VAR2 $VAR3);

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw($VAR2 $VAR3);

sub new {
    my ($package) = @_;
    my $self = {};
    bless ($self, $package);
    return $self;
}

sub SubModules1 {
    my $self = shift;
    if($SUBMODULES->{'1'}) { return $SUBMODULES->{'1'}; }

    # Load & cache submodule
    require Module::SubModule1;
    $SUBMODULES->{'1'} = Module::SubModule1->new(@_);    
    return $SUBMODULES->{'1'};
}

sub SubModules2 {
    my $self = shift;
    if($SUBMODULES->{'2'}) { return $SUBMODULES->{'2'}; }

    # Load & cache submodule
    require Module::SubModule2;
    $SUBMODULES->{'2'} = Module::SubModule2->new(@_);    
    return $SUBMODULES->{'2'};
}

Each submodule is structured as follows:

package Module::SubModule1;

use warnings;
use strict;
use Carp;

use vars qw();

sub new {
    my ($package) = @_;
    my $self = {};
    bless ($self, $package);
    return $self;
}

I want to be able to import the $VAR2 and $VAR3 variables into each of the submodules without having to reference them as $Module::VAR2 and $Module::VAR3. I noticed that the calling script is able to access both the variables that I have exported in Module.pm in the desired fashion but SubModule1.pm and SubModule2.pm still have to reference the variables as being from Module.pm.

I tried updating each submodule as follows which unfortunately didn't work I was hoping:

package Module::SubModule1;

use warnings;
use strict;
use Carp;

use vars qw($VAR2 $VAR3);

sub new {
    my ($package) = @_;
    my $self = {};
    bless ($self, $package);
    $VAR2 = $Module::VAR2;
    $VAR3 = $Module::VAR3;
    return $self;
}

Please let me know how I can successfully export $VAR2 and $VAR3 from Module.pm into each Submodule. Thanks in advance for your help!

Russell C. ,Aug 31, 2010 at 22:37

In your submodules, are you forgetting to say
use Module;

? Calling use Module from another package (say Module::Submodule9 ) will try to run the Module::import method. Since you don't have that method, it will call the Exporter::import method, and that is where the magic that exports Module 's variables into the Module::Submodule9 namespace will happen.


In your program there is only one Module namespace and only one instance of the (global) variable $Module::VAR2 . Exporting creates aliases to this variable in other namespaces, so the same variable can be accessed in different ways. Try this in a separate script:

package Whatever;
use Module;
use strict;
use vars qw($VAR2);

$Module::VAR2 = 5;
print $Whatever::VAR2;    # should be 5.
$VAR2 = 14;               # same as $Whatever::VAR2 = 14
print $Module::VAR2;      # should be 14

Russell C. ,Aug 31, 2010 at 21:38

Well there is the easy way:

In M.pm:

package M;

use strict;
use warnings;

#our is better than "use vars" for creating package variables
#it creates an alias to $M::foo named $foo in the current lexical scope 
our $foo = 5;

sub inM { print "$foo\n" }

1;

In M/S.pm

package M;

#creates an alias to $M::foo that will last for the entire scope,
#in this case the entire file
our $foo;

package M::S;

use strict;
use warnings;

sub inMS { print "$foo\n" }

1;

In the script:

#!/usr/bin/perl

use strict;
use warnings;

use M;
use M::S;

M::inM();
M::S::inMS();

But I would advise against this. Global variables are not a good practice, and sharing global variables between modules is even worse.

[Oct 09, 2019] Package variables

Oct 09, 2019 | perlmaven.com

These are the oldest type of variables in Perl. They are still used in some cases, even though in most cases you should just use lexical variables.

In old times, if we started to use a variable without declaring it with the my or state keywords, we automatically got a variable in the current namespace. Thus we could write:

  1. $x = 42 ;
  2. print "$x\n" ; # 42

Please note, we don't use strict; in these examples. Even though you should always use strict . We'll fix this in a bit.

The default namespace in every perl script is called "main" and you can always access variables using their full name including the namespace:

  1. $x = 42 ;
  2. print "$x\n" ; # 42
  3. print "$main::x\n" ; # 42

The package keyword is used to switch namespaces:

  1. $x = 42 ;
  2. print "$x\n" ; # 42
  3. print "$main::x\n" ; # 42
  4. package Foo ;
  5. print "Foo: $x\n" ; # Foo:

Please note, once we switched to the "Foo" namespace, the $x name refers to the variable in the Foo namespace. It does not have any value yet.

  1. $x = 42 ;
  2. print "$x\n" ; # 42
  3. print "$main::x\n" ; # 42
  4. package Foo ;
  5. print "Foo: $x\n" ; # Foo:
  6. $x = 23 ;
  7. print "Foo: $x\n" ; # Foo 23;

Do we really have two $x-es? Can we reach the $x in the main namespace while we are in the Foo namespace?

  1. $x = 42 ;
  2. print "$x\n" ; # 42
  3. print "$main::x\n" ; # 42
  4. package Foo ;
  5. print "Foo: $x\n" ; # Foo:
  6. $x = 23 ;
  7. print "Foo: $x\n" ; # Foo 23
  8. print "main: $main::x\n" ; # main: 42
  9. print "Foo: $Foo::x\n" ; # Foo: 23
  10. package main ;
  11. print "main: $main::x\n" ; # main: 42
  12. print "Foo: $Foo::x\n" ; # Foo: 23
  13. print "$x\n" ; # 42

We even switched back to the main namespace (using package main; ) and if you look closely, you can see that while we were already in the main package we could reach to the $x of the Foo package using $Foo::x but if we accessed $x without the full package name, we reach the one in the main namespace.

Every package (or namespace) can hold variables with the same name.

[Oct 08, 2019] Perl constant array

Oct 08, 2019 | stackoverflow.com

Ask Question Asked 6 years, 1 month ago Active 4 years ago Viewed 5k times 4 1


Alec ,Sep 5, 2018 at 8:25

use constant {
    COLUMNS => qw/ TEST1 TEST2 TEST3 /,
}

Can I store an array using the constant package in Perl?

Whenever I go on to try to use the array like my @attr = (COLUMNS); , it does not contain the values.

Сухой27 ,Aug 12, 2013 at 13:37

use constant {
  COLUMNS => [qw/ TEST1 TEST2 TEST3 /],
};

print @{+COLUMNS};

> ,

Or remove the curly braces as the docs show :-
  1 use strict;
  2 use constant COLUMNS => qw/ TEST1 TEST2 TEST3 /;
  3 
  4 my @attr = (COLUMNS);
  5 print @attr;

which gives :-

 % perl test.pl
TEST1TEST2TEST3

Your code actually defines two constants COLUMNS and TEST2 :-

use strict;
use constant { COLUMNS => qw/ TEST1 TEST2 TEST3 /, };

my @attr = (COLUMNS);
print @attr;
print TEST2

and gives :-

% perl test.pl
TEST1TEST3

[Sep 30, 2019] int - perldoc.perl.org

Sep 30, 2019 | perldoc.perl.org

[Sep 24, 2019] warn - perldoc.perl.org

Sep 24, 2019 | perldoc.perl.org

Perl 5 version 30.0 documentation warn Perl functions A-Z | Perl functions by category | The 'perlfunc' manpage

[Sep 21, 2019] Namespaces

Sep 21, 2019 | perl.plover.com

Coping with Scoping

© Copyright 1998 The Perl Journal. Reprinted with permission.

Cet article est également disponible en Français

Questo articolo è disponibile anche in Italiano

Dieser Artikel ist auch in deutscher Übersetzung verfügbar


Just the FAQs: Coping with Scoping

In the Beginning, some time around 1960, every part of your program had access to all the variables in every other part of the program. That turned out to be a problem, so language designers invented local variables, which were visible in only a small part of the program. That way, programmers who used a variable x could be sure that nobody was able to tamper with the contents of x behind their back. They could also be sure that by using x they weren't tampering with someone else's variable by mistake.

Every programming language has a philosophy, and these days most of these philosophies have to do with the way the names of variables are managed. Details of which variables are visible to which parts of the program, and what names mean what, and when, are of prime importance. The details vary from somewhat baroque, in languages like Lisp, to extremely baroque, in languages like C++. Perl unfortunately, falls somewhere towards the rococo end of this scale.

The problem with Perl isn't that it has no clearly-defined system of name management, but rather that it two systems, both working at once. Here's the Big Secret about Perl variables that most people learn too late: Perl has two completely separate, independent sets of variables. One is left over from Perl 4, and the other is new. The two sets of variables are called `package variables' and `lexical variables', and they have nothing to do with each other.

Package variables came first, so we'll talk about them first. Then we'll see some problems with package variables, and how lexical variables were introduced in Perl 5 to avoid these problems. Finally, we'll see how to get Perl to automatically diagnose places where you might not be getting the variable you meant to get, which can find mistakes before they turn into bugs.

Package Variables
        $x = 1

Here, $x is a package variable . There are two important things to know about package variables:

  1. Package variables are what you get if you don't say otherwise.
  2. Package variables are always global.

Global means that package variables are always visible everywhere in every program. After you do $x = 1 , any other part of the program, even some other subroutine defined in some other file, can inspect and modify the value of $x . There's no exception to this; package variables are always global.

Package variables are divided into families, called packages . Every package variable has a name with two parts. The two parts are analogous to the variable's given name and family name. You can call the Vice-President of the United States `Al', if you want, but that's really short for his full name, which is `Al Gore'. Similarly, $x has a full name, which is something like $main::x . The main part is the package qualifier , analogous to the `Gore' part of `Al Gore'. Al Gore and Al Capone are different people even though they're both named `Al'. In the same way, $Gore::Al and $Capone::Al are different variables, and $main::x and $DBI::x are different variables.

You're always allowed to include the package part of the variable's name, and if you do, Perl will know exactly which variable you mean. But for brevity, you usually like to leave the package qualifier off. What happens if you do?

The Current Package

If you just say $x , perl assumes that you mean the variable $x in the current package. What's the current package? It's normally main , but you can change the current package by writing

        package Mypackage;

in your program; from that point on, the current package is Mypackage . The only thing the current package does is affect the interpretation of package variables that you wrote without package names. If the current package is Mypackage , then $x really means $Mypackage::x . If the current package is main , then $x really means $main::x.

If you were writing a module, let's say the MyModule module, you would probably put a line like this at the top of the module file:

        package MyModule;

From there on, all the package variables you used in the module file would be in package MyModule , and you could be pretty sure that those variables wouldn't conflict with the variables in the rest of the program. It wouldn't matter if both you and the author of DBI were to use a variable named $x , because one of those $x es would be $MyModule::x and the other would be $DBI::x .

Remember that package variables are always global. Even if you're not in package DBI, even if you've never heard of package DBI, nothing can stop you from reading from or writing to $DBI::errstr . You don't have to do anything special. $DBI::errstr , like all package variables, is a global variable, and it's available globally; all you have to do is mention its full name to get it. You could even say

        package DBI;
        $errstr = 'Ha ha Tim!';

and that would modify $DBI::errstr .

Package Variable Trivia

There are only three other things to know about package variables, and you might want to skip them on the first reading:

  1. The package with the empty name is the same as main . So $::x is the same as $main::x for any x .
  2. Some variables are always forced to be in package main. For example, if you mention %ENV , Perl assumes that you mean %main::ENV , even if the current package isn't main . If you want %Fred::ENV , you have to say so explicitly, even if the current package is Fred . Other names that are special this way include INC , all the one-punctuation-character names like $_ and $$ , @ARGV , and STDIN , STDOUT , and STDERR .
  3. Package names, but not variable names, can contain :: . You can have a variable named $DBD::Oracle::x. This means the variable x in the package DBD::Oracle ; it has nothing at all to do with the package DBD which is unrelated. Isaac Newton is not related to Olivia Newton-John, and Newton::Isaac is not related to Newton::John::Olivia . Even though it appears that they both begin with Newton , the appearance is deceptive. Newton::John::Olivia is in package Newton::John , not package Newton.

That's all there is to know about package variables.

Package variables are global, which is dangerous, because you can never be sure that someone else isn't tampering with them behind your back. Up through Perl 4, all variables were package variables, which was worrisome. So Perl 5 added new variables that aren't global.

Lexical Variables

Perl's other set of variables are called lexical variables (we'll see why later) or private variables because they're private. They're also sometimes called my variables because they're always declared with my . It's tempting to call them `local variables', because their effect is confined to a small part of the program, but don't do that, because people might think you're talking about Perl's local operator, which we'll see later. When you want a `local variable', think my , not local .

The declaration

        my $x;

creates a new variable, named x , which is totally inaccessible to most parts of the program---anything outside the block where the variable was declared. This block is called the scope of the variable. If the variable wasn't declared in any block, its scope is from the place it was declared to the end of the file.

You can also declare and initialize a my variable by writing something like

        my $x = 119;

You can declare and initialize several at once:

        my ($x, $y, $z, @args) = (5, 23, @_);

Let's see an example of where some private variables will be useful. Consider this subroutine:

        sub print_report {
          @employee_list = @_;
          foreach $employee (@employee_list) {
            $salary = lookup_salary($employee);
            print_partial_report($employee, $salary);
          }
        }

If lookup_salary happens to also use a variable named $employee , that's going to be the same variable as the one used in print_report , and the works might get gummed up. The two programmers responsible for print_report and lookup_salary will have to coordinate to make sure they don't use the same variables. That's a pain. In fact, in even a medium-sized project, it's an intolerable pain.

The solution: Use my variables:

        sub print_report {
          my @employee_list = @_;
          foreach my $employee (@employee_list) {
            my $salary = lookup_salary($employee);
            print_partial_report($employee, $salary);
          }
        }

my @employee_list creates a new array variable which is totally inaccessible outside the print_report function. for my $employee creates a new scalar variable which is totally inaccessible outside the foreach loop, as does my $salary . You don't have to worry that the other functions in the program are tampering with these variables, because they can't; they don't know where to find them, because the names have different meanings outside the scope of the my declarations. These `my variables' are sometimes called `lexical' because their scope depends only on the program text itself, and not on details of execution, such as what gets executed in what order. You can determine the scope by inspecting the source code without knowing what it does. Whenever you see a variable, look for a my declaration higher up in the same block. If you find one, you can be sure that the variable is inaccessible outside that block. If you don't find a declaration in the smallest block, look at the next larger block that contains it, and so on, until you do find one. If there is no my declaration anywhere, then the variable is a package variable.

my variables are not package variables. They're not part of a package, and they don't have package qualifiers. The current package has no effect on the way they're interpreted. Here's an example:

        my $x = 17;

        package A;
        $x = 12;

        package B;
        $x = 20;

        # $x is now 20.
        # $A::x and $B::x are still undefined

The declaration my $x = 17 at the top creates a new lexical variable named x whose scope continues to the end of the file. This new meaning of $x overrides the default meaning, which was that $x meant the package variable $x in the current package.

package A changes the current package, but because $x refers to the lexical variable, not to the package variable, $x=12 doesn't have any effect on $A::x . Similarly, after package B , $x=20 modifies the lexical variable, and not any of the package variables.

At the end of the file, the lexical variable $x holds 20, and the package variables $main::x , $A::x , and $B::x are still undefined. If you had wanted them, you could still have accessed them by using their full names.

The maxim you must remember is:

Package variables are global variables.
For private variables, you must use my .

local and my

Almost everyone already knows that there's a local function that has something to do with local variables. What is it, and how does it related to my ? The answer is simple, but bizarre:

my creates a local variable. local doesn't.

First, here's what local $x really does: It saves the current value of the package variable $x in a safe place, and replaces it with a new value, or with undef if no new value was specified. It also arranges for the old value to be restored when control leaves the current block. The variables that it affects are package variables, which get local values. But package variables are always global, and a local package variable is no exception. To see the difference, try this:

        $lo = 'global';
        $m  = 'global';
        A();

        sub A {
          local $lo = 'AAA';
          my    $m  = 'AAA';
          B();
        }

        sub B {
          print "B ", ($lo eq 'AAA' ? 'can' : 'cannot') ,
                " see the value of lo set by A.\n";

          print "B ", ($m  eq 'AAA' ? 'can' : 'cannot') ,
                " see the value of m  set by A.\n";
        }

This prints

        B can see the value of lo set by A.
        B cannot see the value of m  set by A.

What happened here? The local declaration in A saved a new temporary value, AAA , in the package variable $lo . The old value, global , will be restored when A returns, but before that happens, A calls B . B has no problem accessing the contents of $lo , because $lo is a package variable and package variables are always available everywhere, and so it sees the value AAA set by A .

In contrast, the my declaration created a new, lexically scoped variable named $m , which is only visible inside of function A . Outside of A , $m retains its old meaning: It refers the the package variable $m ; which is still set to global . This is the variable that B sees. It doesn't see the AAA because the variable with that value is a lexical variable, and only exists inside of A .

What Good is local ?

Because local does not actually create local variables, it is not very much use. If, in the example above, B happened to modify the value of $lo , then the value set by A would be overwritten. That is exactly what we don't want to happen. We want each function to have its own variables that are untouchable by the others. This is what my does.

Why have local at all? The answer is 90% history. Early versions of Perl only had global variables. local was very easy to implement, and was added to Perl 4 as a partial solution to the local variable problem. Later, in Perl 5, more work was done, and real local variables were put into the language. But the name local was already taken, so the new feature was invoked with the word my . my was chosen because it suggests privacy, and also because it's very short; the shortness is supposed to encourage you to use it instead of local . my is also faster than local .

When to Use my and When to Use local

Always use my ; never use local .

Wasn't that easy?

Other Properties of my Variables

Every time control reaches a my declaration, Perl creates a new, fresh variable. For example, this code prints x=1 fifty times:

        for (1 .. 50) {
          my $x;
          $x++;
          print "x=$x\n";
        }

You get a new $x , initialized to undef , every time through the loop.

If the declaration were outside the loop, control would only pass by it once, so there would only be one variable:

        { my $x;
          for (1 .. 50) {
            $x++;
            print "x=$x\n";
          }     
        }

This prints x=1 , x=2 , x=3 , ... x=50 .

You can use this to play a useful trick. Suppose you have a function that needs to remember a value from one call to the next. For example, consider a random number generator. A typical random number generator (like Perl's rand function) has a seed in it. The seed is just a number. When you ask the random number generator for a random number, the function performs some arithmetic operation that scrambles the seed, and it returns the result. It also saves the result and uses it as the seed for the next time it is called.

Here's typical code: (I stole it from the ANSI C standard, but it behaves poorly, so don't use it for anything important.)

        $seed = 1;
        sub my_rand {
          $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
          return $seed;
        }

And typical output:

        16838
        14666
        10953
        11665
        7451
        26316
        27974
        27550

There's a problem here, which is that $seed is a global variable, and that means we have to worry that someone might inadvertently tamper with it. Or they might tamper with it on purpose, which could affect the rest of the program. What if the function were used in a gambling program, and someone tampered with the random number generator?

But we can't declare $seed as a my variable in the function:

        sub my_rand {
          my $seed;
          $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
          return $seed;
        }

If we did, it would be initialized to undef every time we called my_rand . We need it to retain its value between calls to my_rand .

Here's the solution:

        { my $seed = 1;
          sub my_rand {
            $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
            return $seed;
          }
        }

The declaration is outside the function, so it only happens once, at the time the program is compiled, not every time the function is called. But it's a my variable, and it's in a block, so it's only accessible to code inside the block. my_rand is the only other thing in the block, so the $seed variable is only accessible to the my_rand function.

$seed here is sometimes called a `static' variable, because it stays the same in between calls to the function. (And because there's a similar feature in the C language that is activated by the static keyword.)

my Variable Trivia
  1. You can't declare a variable my if its name is a punctuation character, like $_ , @_ , or $$ . You can't declare the backreference variables $1 , $2 , ... as my . The authors of my thought that that would be too confusing.
  2. Obviously, you can't say my $DBI::errstr , because that's contradictory---it says that the package variable $DBI::errstr is now a lexical variable. But you can say local $DBI::errstr ; it saves the current value of $DBI::errstr and arranges for it to be restored at the end of the block.
  3. New in Perl 5.004, you can write
            foreach my $i (@list) {
    

    instead, to confine the $i to the scope of the loop instead. Similarly,

            for (my $i=0; $i<100; $i++) {
    

    confines the scope of $i to the for loop.

Declarations

If you're writing a function, and you want it to have private variables, you need to declare the variables with my . What happens if you forget?

        sub function {
          $x = 42;        # Oops, should have been my $x = 42.
        }

In this case, your function modifies the global package variable $x . If you were using that variable for something else, it could be a disaster for your program.

Recent versions of Perl have an optional protection against this that you can enable if you want. If you put

        use strict 'vars';

at the top of your program, Perl will require that package variables have an explicit package qualifier. The $x in $x=42 has no such qualifier, so the program won't even compile; instead, the compiler will abort and deliver this error message:

        Global symbol "$x" requires explicit package name at ...

If you wanted $x to be a private my variable, you can go back and add the my . If you really wanted to use the global package variable, you could go back and change it to

        $main::x = 42;

or whatever would be appropriate.

Just saying use strict turns on strict vars , and several other checks besides. See perldoc strict for more details.

Now suppose you're writing the Algorithms::KnuthBendix modules, and you want the protections of strict vars But you're afraid that you won't be able to finish the module because your fingers are starting to fall off from typing $Algorithms::KnuthBendix::Error all the time.

You can save your fingers and tell strict vars to make an exception:

        package Algorithms::KnuthBendix;
        use vars '$Error';

This exempts the package variable $Algorithms::KnuthBendix::Error from causing a strict vars failure if you refer to it by its short name, $Error .

You can also turn strict vars off for the scope of one block by writing

        { no strict 'vars';

          # strict vars is off for the rest of the block.

        }
Summary

Package variables are always global. They have a name and a package qualifier. You can omit the package qualifier, in which case Perl uses a default, which you can set with the package declaration. For private variables, use my . Don't use local ; it's obsolete.

You should avoid using global variables because it can be hard to be sure that no two parts of the program are using one another's variables by mistake.

To avoid using global variables by accident, add use strict 'vars' to your program. It checks to make sure that all variables are either declared private, are explicitly qualified with package qualifiers, or are explicitly declared with use vars .


Glossary
Notes
  1. The tech editors complained about my maxim `Never use local .' But 97% of the time, the maxim is exactly right. local has a few uses, but only a few, and they don't come up too often, so I left them out, because the whole point of a tutorial article is to present 97% of the utility in 50% of the space.

    I was still afraid I'd get a lot of tiresome email from people saying ``You forgot to mention that local can be used for such-and-so, you know.'' So in the colophon at the end of the article, I threatened to deliver Seven Useful Uses for local in three months. I mostly said it to get people off my back about local . But it turned out that I did write it, and it was published some time later.

    The Seven Useful Uses of local is now available on the web site. It appeared in The Perl Journal issue #14.

  2. Here's another potentially interesting matter that I left out for space and clarity. I got email from Robert Watkins with a program he was writing that didn't work. The essence of the bug looked like this:
            my $x;
    
            for $x (1..5) {
              s();
            }
    
            sub s { print "$x, " }
    

    Robert wanted this to print 1, 2, 3, 4, 5, but it did not. Instead, it printed , , , , , . Where did the values of $x go?

    The deal here is that normally, when you write something like this:

                        for $x (...) { }
    

    Perl wants to confine the value of the index variable to inside the loop. If $x is a package variable, it pretends that you wrote this instead:

            { local $x; for $x (...) { } }
    

    But if $x is a lexical variable, it pretends you wrote this instead, instead:

            { my $x;    for $x (...) { } }
    

    This means that the loop index variable won't get propagated to subroutines, even if they're in the scope of the original declaration.

    I probably shouldn't have gone on at such length, because the perlsyn manual page describes it pretty well:

    ...the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my , it uses that variable instead of the global one, but it's still localized to the loop. (Note that a lexically scoped variable can cause problems if you have subroutine or format declarations within the loop which refer to it.)

    In my opinion, lexically scoping the index variable was probably a mistake. If you had wanted that, you would have written for my $x ... in the first place. What I would have liked it to do was to localize the lexical variable: It could save the value of the lexical variable before the loop, and restore it again afterwards. But there may be technical reasons why that couldn't be done, because this doesn't work either:

       my $m;
            { local $m = 12;
              ...
            }
    

    The local fails with this error message:

       Can't localize lexical variable $m...
    

    There's been talk on P5P about making this work, but I gather it's not trivial.

  3. Added 2000-01-05: Perl 5.6.0 introduced a new our(...) declaration. Its syntax is the same as for my() , and it is a replacement for use vars .

    Without getting into the details, our() is just like use vars ; its only effect is to declare variables so that they are exempt from the strict 'vars' checking. It has two possible advantages over use vars , however: Its syntax is less weird, and its effect is lexical. That is, the exception that it creates to the strict checking continues only to the end of the current block:

            use strict 'vars';
            {
              our($x);
              $x = 1;   # Use of global variable $x here is OK
            }
            $x = 2;     # Use of $x here is a compile-time error as usual
    

    So whereas use vars '$x' declares that it is OK to use the global variable $x everywhere, our($x) allows you to say that global $x should be permitted only in certain parts of your program, and should still be flagged as an error if you accidentally use it elsewhere.

  4. Added 2000-01-05: Here's a little wart that takes people by surprise. Consider the following program:
            use strict 'vars';
            my @lines = <>;
            my @sorted = sort backwards @lines;
            print @sorted;
    
            sub backwards { $b cmp $a }
    

    Here we have not declared $a or $b , so they are global variables. In fact, they have to be global, because the sort operator must to be able to set them up for the backwards function. Why doesn't strict produce a failure?

    The variables $a and $b are exempted from strict vars checking, for exactly this reason.

[Sep 21, 2019] Writing PERL Modules - Tutorialspoint

Sep 21, 2019 | www.tutorialspoint.com

What are Packages?

The Package Statement
$i = 1; print "$i\n"; # Prints "1"
package foo;
$i = 2; print "$i\n"; # Prints "2"
package main;
print "$i\n"; # Prints "1"
$PACKAGE_NAME::VARIABLE_NAME

For Example:
$i = 1; print "$i\n"; # Prints "1"
package foo;
$i = 2; print "$i\n"; # Prints "2"
package main;
print "$i\n"; # Prints "1"

print "$foo::i\n"; # Prints "2"
BEGIN and END Blocks

You may define any number of code blocks named BEGIN and END which act as constructors and destructors respectively.

BEGIN { ... }
END { ... }
BEGIN { ... }
END { ... }
What are Perl Modules?

A Perl module is a reusable package defined in a library file whose name is the same as the name of the package (with a .pm on the end).

A Perl module file called "Foo.pm" might contain statements like this.

#!/usr/bin/perl

package Foo;
sub bar { 
   print "Hello $_[0]\n" 
}

sub blat { 
   print "World $_[0]\n" 
}
1;

Few noteable points about modules

The Require Function

A module can be loaded by calling the require function

#!/usr/bin/perl

require Foo;

Foo::bar( "a" );
Foo::blat( "b" );

Notice above that the subroutine names must be fully qualified (because they are isolated in their own package)

It would be nice to enable the functions bar and blat to be imported into our own namespace so we wouldn't have to use the Foo:: qualifier.

The Use Function

A module can be loaded by calling the use function

#!/usr/bin/perl

use Foo;

bar( "a" );
blat( "b" );

Notice that we didn't have to fully qualify the package's function names?

The use function will export a list of symbols from a module given a few added statements inside a module

require Exporter;
@ISA = qw(Exporter);

Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the list variable named @EXPORT : For Example

package Module;

require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(bar blat);

sub bar { print "Hello $_[0]\n" }
sub blat { print "World $_[0]\n" }
sub splat { print "Not $_[0]\n" }  # Not exported!

1;
Create the Perl Module Tree

When you are ready to ship your PERL module then there is standard way of creating a Perl Module Tree. This is done using h2xs utility. This utility comes alongwith PERL. Here is the syntax to use h2xs

$h2xs -AX -n  Module Name

# For example, if your module is available in Person.pm file
$h2xs -AX -n Person

This will produce following result
Writing Person/lib/Person.pm
Writing Person/Makefile.PL
Writing Person/README
Writing Person/t/Person.t
Writing Person/Changes
Writing Person/MANIFEST

Here is the descritpion of these options

So above command creates the following structure inside Person directory. Actual result is shown above.

So finally you tar this directory structure into a file Person.tar and you can ship it. You would have to update README file with the proper instructions. You can provide some test examples files in t directory.

Installing Perl Module

Installing a Perl Module is very easy. Use the following sequence to install any Perl Module.

perl Makefile.PL
make
make install

The Perl interpreter has a list of directories in which it searches for modules (global array @INC)

[Sep 21, 2019] Larry Wall - Present Continuous, Future Perfect - OSDCIsrael Wiki

You can see that Larry Wall bought OO paradigm "hook, line and sinker" , and that was very bad, IMHO disastrous decision. There were several areas were Perl 5 could be more profitably be extended such as exceptions, coroutines and, especially, introducing types of variables. He also did not realize that Javascript prototypes based OO model has much better implementation of OO then Simula-67 model. And that Perl 5 modules do 80% of what is useful in classes (namely provide a separate namespace and the ability to share variables in this namespace between several subroutines)
Notable quotes:
"... Perl 5 had this problem with "do" loops because they weren't real loops - they were a "do" block followed by a statement modifier, and people kept wanting to use loop control it them. Well, we can fix that. "loop" now is a real loop. And it allows a modifier on it but still behaves as a real loop. And so, do goes off to have other duties, and you can write a loop that tests at the end and it is a real loop. And this is just one of many many many things that confused new Perl 5 programmers. ..."
"... We have properties which you can put on variables and onto values. These are generalizations of things that were special code in Perl 5, but now we have general mechanisms to do the same things, they're actually done using a mix-in mechanism like Ruby. ..."
"... Smart match operators is, like Damian say, equal-tilda ("=~") on steroids. Instead of just allowing a regular expression on the right side it allows basically anything, and it figures out that this wants to do a numeric comparison, this wants to do a string comparison, this wants to compare two arrays, this wants to do a lookup in the hash; this wants to call the closure on the right passing in the left argument, and it will tell if you if $x can quack. Now that looks a little strange because you can just say "$x.can('quack')". Why would you do it this way? Well, you'll see. ..."
Feb 26, 2006 | perl.org.il

Irrationalities in Other Languages (5:54)

Now, I'm not the only language designer with irrationalities. You can think of some languages to go with some of these things.

"We've got to start over from scratch" - Well, that's almost any academic language you find.

"English phrases" - We'll that's Cobol. You know, cargo cult English. ( laughter )

"Text processing doesn't matter much" - Fortran.

"Simple languages produce simple solutions" - C.

"If I wanted it fast, I'd write it in C" - That's almost a direct quote from the original awk page.

"I thought of a way to do it so it must be right" - That's obviously PHP. ( laughter and applause )

"You can build anything with NAND gates" - Any language designed by an electrical engineer. ( laughter )

"This is a very high level language, who cares about bits?" - The entire scope of fourth generation languages fell into this... problem.

"Users care about elegance" - A lot of languages from Europe tend to fall into this. You know, Eiffel.

"The specification is good enough" - Ada.

"Abstraction equals usability" - Scheme. Things like that.

"The common kernel should be as small as possible" - Forth.

"Let's make this easy for the computer" - Lisp. ( laughter )

"Most programs are designed top-down" - Pascal. ( laughter )

"Everything is a vector" - APL.

"Everything is an object" - Smalltalk and its children. (whispered:) Ruby. ( laughter )

"Everything is a hypothesis" - Prolog. ( laughter )

"Everything is a function" - Haskell. ( laughter )

"Programmers should never have been given free will" - Obviously, Python. ( laughter )

So my psychological conjecture is that normal people, if they perceive that a computer language is forcing them to learn theory, they won't like it. In other words, hide the fancy stuff. It can be there, just hide it. Fan Mail (14:42)

Q: "Dear Larry, I love Perl. It has saved my company, my crew, my sanity and my marriage. After Perl I can't imagine going back to any other language. I dream in Perl, I tell everyone else about Perl. How can you improve on perfection? Signed, Happy in Haifa."
A: "Dear Happy,
You need to recognize that Perl can be good in some dimensions and not so good in other dimensions. You also need to recognize that there will be some pain in climbing over or tunneling through the barrier to the true minimum."

Now Perl 5 has a few false minima. Syntax, semantics, pragmatics, ( laughter ), discourse structure, implementation, documentation, culture... Other than that Perl 5 is not too bad.

Q: "Dear Larry,
You have often talked about the waterbed theory of linguistic complexity, and beauty times brains equals a constant. Isn't it true that improving Perl in some areas will automatically make it worse in other areas? Signed, Terrified in Tel-Aviv."
A: "Dear Terrified,
...
No." ( laughter )

You see, you can make some things so they aren't any worse. For instance, we changed all the sigils to be more consistent, and they're just the same length, they're just different. And you can make some things much better. Instead of having to write all this gobbledygook to dereference references in Perl 5 you can just do it straight left to right in Perl 6. Or there's even more shortcuts, so multidimensional arrays and constant hash subscripts get their own notation, so it's even clearer, at least once you've learned it. Again, we're optimizing for expressiveness, not necessarily learnability.

Q: "Dear Larry,
I've heard a disturbing rumor that Perl 6 is turning into Java, or Python, or (whispered:) Ruby, or something. What's the point of using Perl if it's just another object-oriented language? Why are we changing the arrow operator to the dot operator? Signed, Nervous in Netanya."
A: "Dear Nervous,
First of all, we can do object orientation better without making other things worse. As I said. Now, we're changing from arrow to dot, because ... because ... Well, just 'cuz I said so!"

You know, actually, we do have some good reasons - it's shorter, it's the industry standard, I wanted the arrow for something else, and I wanted the dot as a secondary sigil. Now we can have it for attributes that have accessors. I also wanted the unary dot for topical type calls, with an assumed object on the left and finally, because I said so. Darn it.

... ... ...

No arbitrary limits round two : Perl started off with the idea that strings should grow infinitely, if you have memory. Just let's get rid of those arbitrary limits that plagued Unix utilities in the early years. Perl 6 is taking this in a number of different dimensions than just how long your strings are. No arbitrary limits - you ought to be able to program very abstractly, you ought to be able to program very concretely - that's just one dimension.

... .. ...

Perl 5 is just all full of these strange gobbledygooky variables which we all know and love - and hate. So the error variables are now unified into a single error variable. These variables have been deprecated forever, they're gone! These weird things that just drive syntax highlighters nuts ( laughter ) now actually have more regular names. The star there, $*GID, that's what we call a secondary sigil, what that just says is this is in the global namespace. So we know that that's a global variable for the entire process. Similarly for uids.

... ... ...

Perl 5 had this problem with "do" loops because they weren't real loops - they were a "do" block followed by a statement modifier, and people kept wanting to use loop control it them. Well, we can fix that. "loop" now is a real loop. And it allows a modifier on it but still behaves as a real loop. And so, do goes off to have other duties, and you can write a loop that tests at the end and it is a real loop. And this is just one of many many many things that confused new Perl 5 programmers.

... ... ...

Perl 5, another place where it was too orthogonal - we defined parameter passing to just come in as an array. You know arrays, subroutines - they're just orthogonal. You just happen to have one called @_, which your parameters come in, and it was wonderfully orthogonal, and people built all sorts of stuff on top of it, and it's another place where we are changing.

... .. ...

Likewise, if you turn them inside out - the french quotes - you can use the regular angle brackets, and yes, we did change here-docs so it does not conflict, then that's the equivalent of "qw". This qw interpolates, with single-angles it does not interpolate - that is the exact "qw".

We have properties which you can put on variables and onto values. These are generalizations of things that were special code in Perl 5, but now we have general mechanisms to do the same things, they're actually done using a mix-in mechanism like Ruby.

Smart match operators is, like Damian say, equal-tilda ("=~") on steroids. Instead of just allowing a regular expression on the right side it allows basically anything, and it figures out that this wants to do a numeric comparison, this wants to do a string comparison, this wants to compare two arrays, this wants to do a lookup in the hash; this wants to call the closure on the right passing in the left argument, and it will tell if you if $x can quack. Now that looks a little strange because you can just say "$x.can('quack')". Why would you do it this way? Well, you'll see.

... ... ..

There's a lot of cruft that we inherited from the UNIX culture and we added more cruft, and we're cleaning it up. So in Perl 5 we made the mistake of interpreting regular expressions as strings, which means we had to do weird things like back-references are \1 on the left, but they're $1 on the right, even though it means the same thing. In Perl 6, because it's just a language, (an embedded language) $1 is the back-reference. It does not automatically interpolate this $1 from what it was before. You can also get it translated to Euros I guess.

[Sep 21, 2019] Dr. Dobb's Journal February 1998 A Conversation with Larry Wall

Perl is unique complex non-orthogonal language and due to this it has unique level of expressiveness.
Also the complexity of Perl to a large extent reflect the complexity of Perl environment (which is Unix environment at the beginning, but now also Windows environment with its quirks)
Notable quotes:
"... On a syntactic level, in the particular case of Perl, I placed variable names in a separate namespace from reserved words. That's one of the reasons there are funny characters on the front of variable names -- dollar signs and so forth. That allowed me to add new reserved words without breaking old programs. ..."
"... A script is something that is easy to tweak, and a program is something that is locked in. There are all sorts of metaphorical tie-ins that tend to make programs static and scripts dynamic, but of course, it's a continuum. You can write Perl programs, and you can write C scripts. People do talk more about Perl programs than C scripts. Maybe that just means Perl is more versatile. ..."
"... A good language actually gives you a range, a wide dynamic range, of your level of discipline. We're starting to move in that direction with Perl. The initial Perl was lackadaisical about requiring things to be defined or declared or what have you. Perl 5 has some declarations that you can use if you want to increase your level of discipline. But it's optional. So you can say "use strict," or you can turn on warnings, or you can do various sorts of declarations. ..."
"... But Perl was an experiment in trying to come up with not a large language -- not as large as English -- but a medium-sized language, and to try to see if, by adding certain kinds of complexity from natural language, the expressiveness of the language grew faster than the pain of using it. And, by and large, I think that experiment has been successful. ..."
"... If you used the regular expression in a list context, it will pass back a list of the various subexpressions that it matched. A different computer language may add regular expressions, even have a module that's called Perl 5 regular expressions, but it won't be integrated into the language. You'll have to jump through an extra hoop, take that right angle turn, in order to say, "Okay, well here, now apply the regular expression, now let's pull the things out of the regular expression," rather than being able to use the thing in a particular context and have it do something meaningful. ..."
"... A language is not a set of syntax rules. It is not just a set of semantics. It's the entire culture surrounding the language itself. So part of the cultural context in which you analyze a language includes all the personalities and people involved -- how everybody sees the language, how they propagate the language to other people, how it gets taught, the attitudes of people who are helping each other learn the language -- all of this goes into the pot of context. ..."
"... In the beginning, I just tried to help everybody. Particularly being on USENET. You know, there are even some sneaky things in there -- like looking for people's Perl questions in many different newsgroups. For a long time, I resisted creating a newsgroup for Perl, specifically because I did not want it to be ghettoized. You know, if someone can say, "Oh, this is a discussion about Perl, take it over to the Perl newsgroup," then they shut off the discussion in the shell newsgroup. If there are only the shell newsgroups, and someone says, "Oh, by the way, in Perl, you can solve it like this," that's free advertising. So, it's fuzzy. We had proposed Perl as a newsgroup probably a year or two before we actually created it. It eventually came to the point where the time was right for it, and we did that. ..."
"... For most web applications, Perl is severely underutilized. Your typical CGI script says print, print, print, print, print, print, print. But in a sense, it's the dynamic range of Perl that allows for that. You don't have to say a whole lot to write a simple Perl script, whereas your minimal Java program is, you know, eight or ten lines long anyway. Many of the features that made it competitive in the UNIX space will make it competitive in other spaces. ..."
"... Over the years, much of the work of making Perl work for people has been in designing ways for people to come to Perl. I actually delayed the first version of Perl for a couple of months until I had a sed-to-Perl and an awk-to-Perl translator. One of the benefits of borrowing features from various other languages is that those subsets of Perl that use those features are familiar to people coming from that other culture. What would be best, in my book, is if someone had a way of saying, "Well, I've got this thing in Visual Basic. Now, can I just rewrite some of these things in Perl?" ..."
Feb 28, 1998 | www.ddj.com

... ... ...

The creator of Perl talks about language design and Perl. By Eugene Eric Kim

DDJ : Is Perl 5.005 what you envisioned Perl to be when you set out to do it?

LW: That assumes that I'm smart enough to envision something as complicated as Perl. I knew that Perl would be good at some things, and would be good at more things as time went on. So, in a sense, I'm sort of blessed with natural stupidity -- as opposed to artificial intelligence -- in the sense that I know what my intellectual limits are.

I'm not one of these people who can sit down and design an entire system from scratch and figure out how everything relates to everything else, so I knew from the start that I had to take the bear-of-very-little-brain approach, and design the thing to evolve. But that fit in with my background in linguistics, because natural languages evolve over time.

You can apply biological metaphors to languages. They move into niches, and as new needs arise, languages change over time. It's actually a practical way to design a computer language. Not all computer programs can be designed that way, but I think more can be designed that way than have been. A lot of the majestic failures that have occurred in computer science have been because people thought they could design the whole thing in advance.

DDJ : How do you design a language to evolve?

LW: There are several aspects to that, depending on whether you are talking about syntax or semantics. On a syntactic level, in the particular case of Perl, I placed variable names in a separate namespace from reserved words. That's one of the reasons there are funny characters on the front of variable names -- dollar signs and so forth. That allowed me to add new reserved words without breaking old programs.

DDJ : What is a scripting language? Does Perl fall into the category of a scripting language?

LW: Well, being a linguist, I tend to go back to the etymological meanings of "script" and "program," though, of course, that's fallacious in terms of what they mean nowadays. A script is what you hand to the actors, and a program is what you hand to the audience. Now hopefully, the program is already locked in by the time you hand that out, whereas the script is something you can tinker with. I think of phrases like "following the script," or "breaking from the script." The notion that you can evolve your script ties into the notion of rapid prototyping.

A script is something that is easy to tweak, and a program is something that is locked in. There are all sorts of metaphorical tie-ins that tend to make programs static and scripts dynamic, but of course, it's a continuum. You can write Perl programs, and you can write C scripts. People do talk more about Perl programs than C scripts. Maybe that just means Perl is more versatile.

... ... ...

DDJ : Would that be a better distinction than interpreted versus compiled -- run-time versus compile-time binding?

LW: It's a more useful distinction in many ways because, with late-binding languages like Perl or Java, you cannot make up your mind about what the real meaning of it is until the last moment. But there are different definitions of what the last moment is. Computer scientists would say there are really different "latenesses" of binding.

A good language actually gives you a range, a wide dynamic range, of your level of discipline. We're starting to move in that direction with Perl. The initial Perl was lackadaisical about requiring things to be defined or declared or what have you. Perl 5 has some declarations that you can use if you want to increase your level of discipline. But it's optional. So you can say "use strict," or you can turn on warnings, or you can do various sorts of declarations.

DDJ : Would it be accurate to say that Perl doesn't enforce good design?

LW: No, it does not. It tries to give you some tools to help if you want to do that, but I'm a firm believer that a language -- whether it's a natural language or a computer language -- ought to be an amoral artistic medium.

You can write pretty poems or you can write ugly poems, but that doesn't say whether English is pretty or ugly. So, while I kind of like to see beautiful computer programs, I don't think the chief virtue of a language is beauty. That's like asking an artist whether they use beautiful paints and a beautiful canvas and a beautiful palette. A language should be a medium of expression, which does not restrict your feeling unless you ask it to.

DDJ : Where does the beauty of a program lie? In the underlying algorithms, in the syntax of the description?

LW: Well, there are many different definitions of artistic beauty. It can be argued that it's symmetry, which in a computer language might be considered orthogonality. It's also been argued that broken symmetry is what is considered most beautiful and most artistic and diverse. Symmetry breaking is the root of our whole universe according to physicists, so if God is an artist, then maybe that's his definition of what beauty is.

This actually ties back in with the built-to-evolve concept on the semantic level. A lot of computer languages were defined to be naturally orthogonal, or at least the computer scientists who designed them were giving lip service to orthogonality. And that's all very well if you're trying to define a position in a space. But that's not how people think. It's not how natural languages work. Natural languages are not orthogonal, they're diagonal. They give you hypotenuses.

Suppose you're flying from California to Quebec. You don't fly due east, and take a left turn over Nashville, and then go due north. You fly straight, more or less, from here to there. And it's a network. And it's actually sort of a fractal network, where your big link is straight, and you have little "fractally" things at the end for your taxi and bicycle and whatever the mode of transport you use. Languages work the same way. And they're designed to get you most of the way here, and then have ways of refining the additional shades of meaning.

When they first built the University of California at Irvine campus, they just put the buildings in. They did not put any sidewalks, they just planted grass. The next year, they came back and built the sidewalks where the trails were in the grass. Perl is that kind of a language. It is not designed from first principles. Perl is those sidewalks in the grass. Those trails that were there before were the previous computer languages that Perl has borrowed ideas from. And Perl has unashamedly borrowed ideas from many, many different languages. Those paths can go diagonally. We want shortcuts. Sometimes we want to be able to do the orthogonal thing, so Perl generally allows the orthogonal approach also. But it also allows a certain number of shortcuts, and being able to insert those shortcuts is part of that evolutionary thing.

I don't want to claim that this is the only way to design a computer language, or that everyone is going to actually enjoy a computer language that is designed in this way. Obviously, some people speak other languages. But Perl was an experiment in trying to come up with not a large language -- not as large as English -- but a medium-sized language, and to try to see if, by adding certain kinds of complexity from natural language, the expressiveness of the language grew faster than the pain of using it. And, by and large, I think that experiment has been successful.

DDJ : Give an example of one of the things you think is expressive about Perl that you wouldn't find in other languages.

LW: The fact that regular-expression parsing and the use of regular expressions is built right into the language. If you used the regular expression in a list context, it will pass back a list of the various subexpressions that it matched. A different computer language may add regular expressions, even have a module that's called Perl 5 regular expressions, but it won't be integrated into the language. You'll have to jump through an extra hoop, take that right angle turn, in order to say, "Okay, well here, now apply the regular expression, now let's pull the things out of the regular expression," rather than being able to use the thing in a particular context and have it do something meaningful.

The school of linguistics I happened to come up through is called tagmemics, and it makes a big deal about context. In a real language -- this is a tagmemic idea -- you can distinguish between what the conventional meaning of the "thing" is and how it's being used. You think of "dog" primarily as a noun, but you can use it as a verb. That's the prototypical example, but the "thing" applies at many different levels. You think of a sentence as a sentence. Transformational grammar was built on the notion of analyzing a sentence. And they had all their cute rules, and they eventually ended up throwing most of them back out again.

But in the tagmemic view, you can take a sentence as a unit and use it differently. You can say a sentence like, "I don't like your I-can-use-anything-like-a-sentence attitude." There, I've used the sentence as an adjective. The sentence isn't an adjective if you analyze it, any way you want to analyze it. But this is the way people think. If there's a way to make sense of something in a particular context, they'll do so. And Perl is just trying to make those things make sense. There's the basic distinction in Perl between singular and plural context -- call it list context and scalar context, if you will. But you can use a particular construct in a singular context that has one meaning that sort of makes sense using the list context, and it may have a different meaning that makes sense in the plural context.

That is where the expressiveness comes from. In English, you read essays by people who say, "Well, how does this metaphor thing work?" Owen Barfield talks about this. You say one thing and mean another. That's how metaphors arise. Or you take two things and jam them together. I think it was Owen Barfield, or maybe it was C.S. Lewis, who talked about "a piercing sweetness." And we know what "piercing" is, and we know what "sweetness" is, but you put those two together, and you've created a new meaning. And that's how languages ought to work.

DDJ : Is a more expressive language more difficult to learn?

LW: Yes. It was a conscious tradeoff at the beginning of Perl that it would be more difficult to master the whole language. However, taking another clue from a natural language, we do not require 5-year olds to speak with the same diction as 50-year olds. It is okay for you to use the subset of a language that you are comfortable with, and to learn as you go. This is not true of so many computer-science languages. If you program C++ in a subset that corresponds to C, you get laughed out of the office.

There's a whole subject that we haven't touched here. A language is not a set of syntax rules. It is not just a set of semantics. It's the entire culture surrounding the language itself. So part of the cultural context in which you analyze a language includes all the personalities and people involved -- how everybody sees the language, how they propagate the language to other people, how it gets taught, the attitudes of people who are helping each other learn the language -- all of this goes into the pot of context.

Because I had already put out other freeware projects (rn and patch), I realized before I ever wrote Perl that a great deal of the value of those things was from collaboration. Many of the really good ideas in rn and Perl came from other people.

I think that Perl is in its adolescence right now. There are places where it is grown up, and places where it's still throwing tantrums. I have a couple of teenagers, and the thing you notice about teenagers is that they're always plus or minus ten years from their real age. So if you've got a 15-year old, they're either acting 25 or they're acting 5. Sometimes simultaneously! And Perl is a little that way, but that's okay.

DDJ : What part of Perl isn't quite grown up?

LW: Well, I think that the part of Perl, which has not been realistic up until now has been on the order of how you enable people in certain business situations to actually use it properly. There are a lot of people who cannot use freeware because it is, you know, schlocky. Their bosses won't let them, their government won't let them, or they think their government won't let them. There are a lot of people who, unknown to their bosses or their government, are using Perl.

DDJ : So these aren't technical issues.

LW: I suppose it depends on how you define technology. Some of it is perceptions, some of it is business models, and things like that. I'm trying to generate a new symbiosis between the commercial and the freeware interests. I think there's an artificial dividing line between those groups and that they could be more collaborative.

As a linguist, the generation of a linguistic culture is a technical issue. So, these adjustments we might make in people's attitudes toward commercial operations or in how Perl is being supported, distributed, advertised, and marketed -- not in terms of trying to make bucks, but just how we propagate the culture -- these are technical ideas in the psychological and the linguistic sense. They are, of course, not technical in the computer-science sense. But I think that's where Perl has really excelled -- its growth has not been driven solely by technical merits.

DDJ : What are the things that you do when you set out to create a culture around the software that you write?

LW: In the beginning, I just tried to help everybody. Particularly being on USENET. You know, there are even some sneaky things in there -- like looking for people's Perl questions in many different newsgroups. For a long time, I resisted creating a newsgroup for Perl, specifically because I did not want it to be ghettoized. You know, if someone can say, "Oh, this is a discussion about Perl, take it over to the Perl newsgroup," then they shut off the discussion in the shell newsgroup. If there are only the shell newsgroups, and someone says, "Oh, by the way, in Perl, you can solve it like this," that's free advertising. So, it's fuzzy. We had proposed Perl as a newsgroup probably a year or two before we actually created it. It eventually came to the point where the time was right for it, and we did that.

DDJ : Perl has really been pigeonholed as a language of the Web. One result is that people mistakenly try to compare Perl to Java. Why do you think people make the comparison in the first place? Is there anything to compare?

LW: Well, people always compare everything.

DDJ : Do you agree that Perl has been pigeonholed?

LW: Yes, but I'm not sure that it bothers me. Before it was pigeonholed as a web language, it was pigeonholed as a system-administration language, and I think that -- this goes counter to what I was saying earlier about marketing Perl -- if the abilities are there to do a particular job, there will be somebody there to apply it, generally speaking. So I'm not too worried about Perl moving into new ecological niches, as long as it has the capability of surviving in there.

Perl is actually a scrappy language for surviving in a particular ecological niche. (Can you tell I like biological metaphors?) You've got to understand that it first went up against C and against shell, both of which were much loved in the UNIX community, and it succeeded against them. So that early competition actually makes it quite a fit competitor in many other realms, too.

For most web applications, Perl is severely underutilized. Your typical CGI script says print, print, print, print, print, print, print. But in a sense, it's the dynamic range of Perl that allows for that. You don't have to say a whole lot to write a simple Perl script, whereas your minimal Java program is, you know, eight or ten lines long anyway. Many of the features that made it competitive in the UNIX space will make it competitive in other spaces.

Now, there are things that Perl can't do. One of the things that you can't do with Perl right now is compile it down to Java bytecode. And if that, in the long run, becomes a large ecological niche (and this is not yet a sure thing), then that is a capability I want to be certain that Perl has.

DDJ : There's been a movement to merge the two development paths between the ActiveWare Perl for Windows and the main distribution of Perl. You were talking about ecological niches earlier, and how Perl started off as a text-processing language. The scripting languages that are dominant on the Microsoft platforms -- like VB -- tend to be more visual than textual. Given Perl's UNIX origins -- awk, sed, and C, for that matter -- do you think that Perl, as it currently stands, has the tools to fit into a Windows niche?

LW: Yes and no. It depends on your problem domain and who's trying to solve the problem. There are problems that only need a textual solution or don't need a visual solution. Automation things of certain sorts don't need to interact with the desktop, so for those sorts of things -- and for the programmers who aren't really all that interested in visual programming -- it's already good for that. And people are already using it for that. Certainly, there is a group of people who would be enabled to use Perl if it had more of a visual interface, and one of the things we're talking about doing for the O'Reilly NT Perl Resource Kit is some sort of a visual interface.

A lot of what Windows is designed to do is to get mere mortals from 0 to 60, and there are some people who want to get from 60 to 100. We are not really interested in being in Microsoft's crosshairs. We're not actually interested in competing head-to-head with Visual Basic, and to the extent that we do compete with them, it's going to be kind of subtle. There has to be some way to get people from the slow lane to the fast lane. It's one thing to give them a way to get from 60 to 100, but if they have to spin out to get from the slow lane to the fast lane, then that's not going to work either.

Over the years, much of the work of making Perl work for people has been in designing ways for people to come to Perl. I actually delayed the first version of Perl for a couple of months until I had a sed-to-Perl and an awk-to-Perl translator. One of the benefits of borrowing features from various other languages is that those subsets of Perl that use those features are familiar to people coming from that other culture. What would be best, in my book, is if someone had a way of saying, "Well, I've got this thing in Visual Basic. Now, can I just rewrite some of these things in Perl?"

We're already doing this with Java. On our UNIX Perl Resource Kit, I've got a hybrid language called "jpl" -- that's partly a pun on my old alma mater, Jet Propulsion Laboratory, and partly for Java, Perl...Lingo, there we go! That's good. "Java Perl Lingo." You've heard it first here! jpl lets you take a Java program and magically turn one of the methods into a chunk of Perl right there inline. It turns Perl code into a native method, and automates the linkage so that when you pull in the Java code, it also pulls in the Perl code, and the interpreter, and everything else. It's actually calling out from Java's Virtual Machine into Perl's virtual machine. And we can call in the other direction, too. You can embed Java in Perl, except that there's a bug in JDK having to do with threads that prevents us from doing any I/O. But that's Java's problem.

It's a way of letting somebody evolve from a purely Java solution into, at least partly, a Perl solution. It's important not only to make Perl evolve, but to make it so that people can evolve their own programs. It's how I program, and I think a lot of people program that way. Most of us are too stupid to know what we want at the beginning.

DDJ : Is there hope down the line to present Perl to a standardization body?

LW: Well, I have said in jest that people will be free to standardize Perl when I'm dead. There may come a time when that is the right thing to do, but it doesn't seem appropriate yet.

DDJ : When would that time be?

LW: Oh, maybe when the federal government declares that we can't export Perl unless it's standardized or something.

DDJ : Only when you're forced to, basically.

LW: Yeah. To me, once things get to a standards body, it's not very interesting anymore. The most efficient form of government is a benevolent dictatorship. I remember walking into some BOF that USENIX held six or seven years ago, and John Quarterman was running it, and he saw me sneak in, sit in the back corner, and he said, "Oh, here comes Larry Wall! He's a standards committee all of his own!"

A great deal of the success of Perl so far has been based on some of my own idiosyncrasies. And I recognize that they are idiosyncrasies, and I try to let people argue me out of them whenever appropriate. But there are still ways of looking at things that I seem to do differently than anybody else. It may well be that perl5-porters will one day degenerate into a standards committee. So far, I have not abused my authority to the point that people have written me off, and so I am still allowed to exercise a certain amount of absolute power over the Perl core.

I just think headless standards committees tend to reduce everything to mush. There is a conservatism that committees have that individuals don't, and there are times when you want to have that conservatism and times you don't. I try to exercise my authority where we don't want that conservatism. And I try not to exercise it at other times.

DDJ : How did you get involved in computer science? You're a linguist by background?

LW: Because I talk to computer scientists more than I talk to linguists, I wear the linguistics mantle more than I wear the computer-science mantle, but they actually came along in parallel, and I'm probably a 50/50 hybrid. You know, basically, I'm no good at either linguistics or computer science.

DDJ : So you took computer-science courses in college?

LW: In college, yeah. In college, I had various majors, but what I eventually graduated in -- I'm one of those people that packed four years into eight -- what I eventually graduated in was a self-constructed major, and it was Natural and Artificial Languages, which seems positively prescient considering where I ended up.

DDJ : When did you join O'Reilly as a salaried employee? And how did that come about?

LW: A year-and-a-half ago. It was partly because my previous job was kind of winding down.

DDJ : What was your previous job?

LW: I was working for Seagate Software. They were shutting down that branch of operations there. So, I was just starting to look around a little bit, and Tim noticed me looking around and said, "Well, you know, I've wanted to hire you for a long time," so we talked. And Gina Blaber (O'Reilly's software director) and I met. So, they more or less offered to pay me to mess around with Perl.

So it's sort of my dream job. I get to work from home, and if I feel like taking a nap in the afternoon, I can take a nap in the afternoon and work all night.

DDJ : Do you have any final comments, or tips for aspiring programmers? Or aspiring Perl programmers?

LW: Assume that your first idea is wrong, and try to think through the various options. I think that the biggest mistake people make is latching onto the first idea that comes to them and trying to do that. It really comes to a thing that my folks taught me about money. Don't buy something unless you've wanted it three times. Similarly, don't throw in a feature when you first think of it. Think if there's a way to generalize it, think if it should be generalized. Sometimes you can generalize things too much. I think like the things in Scheme were generalized too much. There is a level of abstraction beyond which people don't want to go. Take a good look at what you want to do, and try to come up with the long-term lazy way, not the short-term lazy way.

[Sep 21, 2019] Half my life with Perl by Randal L. Schwartz

Sep 21, 2019 | www.socallinuxexpo.org

... ... ...

Derailed to an unexpectedly good outcome


Larry Wall


Perl 1


Perl 2


Trolling Usenet

... ... ...


Birth of a camel


Writing the camel


Release the camel!


[Sep 21, 2019] How Did Perl Lose Ground to Bash?

Notable quotes:
"... It baffles me the most because the common objection to Perl is legibility. Even if you assume that the objection is made from ignorance - i.e. not even having looked at some Perl to gauge its legibility - the nonsense you see in a complex bash script is orders of magnitude worse! ..."
"... Maybe it's not reassuring to hear that, but I took an interest in Perl precisely because it's seen as an underdog and "dead" despite having experienced users and a lot of code, kind of like TCL, Prolog, or Ada. ..."
"... There's a long history of bad code written by mediocre developers who became the only one who could maintain the codebase until they no longer worked for the organization. The next poor sap to go in found a mess of a codebase and did their best to not break it further. After a few iterations, the whole thing is ready for /dev/null and Perl gets the blame. ..."
"... All in all, Perl is still my first go-to language, but there are definitely some things I wish it did better. ..."
"... The Perl leadership Osborned itself with Perl6. 20/20 hindsight says the new project should have been given a different name at conception, that way all the "watch this space -- under construction" signage wouldn't have steered people away from perfectly usable Perl5. Again, IMO. ..."
"... I don't observe the premise at all though. Is bash really gaining ground over anything recently? ..."
"... Python again is loved, because "taught by rote" idiots. Now you can give them pretty little packages. And it's no wonder they can do little better than be glorified system admins (which id rather have a real sys admin, since he's likely to understand Perl) ..."
"... Making a new language means lots of new training. Lots of profit in this. Nobody profits from writing new books on old languages. Lots of profit in general from supporting a new language. In the end, owning the language gets you profits. ..."
"... And I still don't get why tab for blocks python is even remotely more readable than Perl. ..."
"... If anything, JavaScript is pretty dang godly at what it does, I understand why that's popular. But I don't get python one bit, except to employ millions of entry level minions who can't think on their own. ..."
"... "Every teacher I know has students using it. We do it because it's an easy language, there's only one way to do it, and with whitespace as syntax it's easy to grade. We don't teach it because it is some powerful or exceptional language. " ..."
Sep 21, 2019 | www.reddit.com

How Did Perl Lose Ground to Bash?

Setting aside Perl vs. Python for the moment, how did Perl lose ground to Bash? It used to be that Bash scripts often got replaced by Perl scripts because Perl was more powerful. Even with very modern versions of Bash, Perl is much more powerful.

The Linux Standards Base (LSB) has helped ensure that certain tools are in predictable locations. Bash has gotten a bit more powerful since the release of 4.x, sure. Arrays, handicapped to 2-D arrays, have improved somewhat. There is a native regex engine in Bash 3.x, which admit is a big deal. There is also support for hash maps.

This is all good stuff for Bash. But, none of this is sufficient to explain why Perl isn't the thing you learn after Bash, or, after Bash and Python; take your pick. Thoughts?

28 comments 75% Upvoted What are your thoughts? Log in or Sign up log in sign up Sort by

oldmanwillow21 9 points · 9 days ago

Because Perl has suffered immensely in the popularity arena and is now viewed as undesirable. It's not that Bash is seen as an adequate replacement for Perl, that's where Python has landed.

emilper 8 points · 8 days ago

How did Perl5 lose ground to anything else?

Thusly

- "thou must use Moose for everything" -> "Perl is too slow" -> rewrite in Python because the architect loves Python -> Python is even slower -> architect shunned by the team and everything new written in Go, nobody dares to complain about speed now because the budget people don't trust them -> Perl is slow

- "globals are bad, singletons are good" -> spaghetti -> Perl is unreadable

- "lets use every single item from the gang of four book" -> insanity -> Perl is bad

- "we must be more OOP" -> everything is a faux object with everything else as attributes -> maintenance team quits and they all take PHP jobs, at least the PHP people know their place in the order of things and do less hype-driven-development -> Perl is not OOP enough

- "CGI is bad" -> app needs 6.54GB of RAM for one worker -> customer refuses to pay for more RAM, fires the team, picks a PHP team to do the next version -> PHP team laughs all the way to the bank, chanting "CGI is king"

recrof 2 points · 8 days ago

"CGI is bad" is real. PSGI or FCGI is much faster for web services, and if there are memory leaks, it's always possible to debug & fix them.

Grinnz 6 points · 8 days ago

CGI is fine, when it's all you need. There are many different use cases out there. Just don't use CGI.pm .

emilper 2 points · 7 days ago

memory leaks

memory leaks ... do huge monoliths count as "memory leaks" ?

Altreus 7 points · 8 days ago

It baffles me the most because the common objection to Perl is legibility. Even if you assume that the objection is made from ignorance - i.e. not even having looked at some Perl to gauge its legibility - the nonsense you see in a complex bash script is orders of magnitude worse!

Not to mention its total lack of common language features like first-class data and... Like, a compiler...

I no longer write bash scripts because it takes about 5 lines to become unmaintainable.

crashorbit 5 points · 9 days ago

Every language that reaches functional equity with Perl is perceived as better than it. Mostly because hey, at least it's not Perl.

oldmanwillow21 15 points · 9 days ago · edited 9 days ago

Jumbled mess of thoughts surely to follow.

When I discuss projects with peers and mention that I chose to develop in Perl, the responses range from passive bemusement, to scorn, to ridicule. The assumption is usually that I'm using a dead language that's crippled in functionality and uses syntax that will surely make everyone's eyes bleed to read. This is the culture everywhere from the casual hackers to the C-suite.

I've proven at work that I can write nontrivial software using Perl. I'm still asked to use Python or Go (edit: or node, ugh) for any project that'll have contributors from other teams, or to containerize apps using Docker to remove the need for Perl knowledge for end-users (no CPAN, carton, etc.). But I'll take what I can get, and now the attitude has gone from "get with the times" or "that's cute", to "ok but I don't expect everyone else to know it".

Perl has got a lot to offer, and I vastly enjoy using it over other languages I work with. I know that all the impassioned figures in the Perl community love it just the same, but the community's got some major fragmentation going on. I understand that everyone's got ideas about the future of the language, but is this really the best time to pull the community apart? I feel like if everyone was able to let go of their ego and put their heads together to bring us to a point of stability, even a place where we're not laughed at for professing our support for the language, it would be a major step in the right direction. I think we're heading to the bottom fast, otherwise.

In that spirit of togetherness, I think the language, particularly the community, needs to be made more accessible to newcomers. Not accessible to one Perl offshoot, but accessible to Perl. It needs to be decided what Perl means in today's day and age. What can it do? Why would I want to use it over another shiny language? What are the definitive places I can go to learn more? Who else will be there? How do I contribute and grow as a Perl developer? There need to be people talking about Perl in places that aren't necessarily hubs for other Perl enthusiasts. It needs to be something business decision-makers can look at and feel confident in using.

I really hope something changes. I'd be pretty sad if I had to spend the rest of my career writing whatever the trendy language of the day is. These are just observations from someone that likes writing Perl and has been watching from the sidelines.

PhloxPaniculata 2 points · 7 days ago

Maybe it's not reassuring to hear that, but I took an interest in Perl precisely because it's seen as an underdog and "dead" despite having experienced users and a lot of code, kind of like TCL, Prolog, or Ada.

Being able to read Modern Perl for free also helped a lot. I'm still lacking experience in Perl and I've yet to write anything of importance in it because I don't see an area in which it's clearly better than anything else, either because of the language, a package, or a framework, and I don't do a lot of text-munging anymore (I'm also a fan of awk so for small tasks it has the priority).

codon011 1 point · 9 days ago

Don't call it Perl. Unfortunately. Also IME multitasking in Perl5 (or the lack thereof and/or severe issues with) has been a detriment to it's standing in a "multithread all the things" world.

crashorbit 4 points · 8 days ago

So often I see people drag themselves down that "thread my app" path. Eventually realize that they are implementing a whole multi-processing operating system inside their app rather than taking advantage of the perfectly good one they are running on.

There are several perfectly good ways to do concurrency, multitasking, async IO and so on in perl. Many work well in the single node case and in the multi-node case. Anyone who tells you that multitasking systems are easy because of some implementation language choice has not made it through the whole Dunning Kruger cycle yet.

codon011 2 points · 8 days ago

Multithreading is never easy. The processors will always manage to do things in a "wrong" order unless you are very careful with your gatekeeping. However, other languages/frameworks have paradigms that make it seem easier such that those race conditions show up much later in your product lifecycle.

codon011 3 points · 9 days ago

There's a long history of bad code written by mediocre developers who became the only one who could maintain the codebase until they no longer worked for the organization. The next poor sap to go in found a mess of a codebase and did their best to not break it further. After a few iterations, the whole thing is ready for /dev/null and Perl gets the blame.

Bash has limitations, but that (usually) means fewer ways to mess it up. There's less domain knowledge to learn, (afaik) no CPAN equivalent, and fewer issues with things like "I need to upgrade this but I can't because this other thing uses this older version which is incompatible with the newer version so now we have to maintain two versions of the library and/or interpreter."

All in all, Perl is still my first go-to language, but there are definitely some things I wish it did better.

crb3 3 points · 9 days ago · edited 9 days ago

*[e:] Consider, not just core here, but CPAN pull-in as well. I had one project clobbered on a smaller-memory machine when I tried to set up a pure-Perl scp transfer -- there wasn't room enough for the full file to transfer if it was larger than about 50k, what with all the CPAN. Shelling to commandline scp worked just fine.

beermad 2 points · 8 days ago

To be fair, wrapping a Perl script around something that's (if I read your comment right) just running SCP is adding a pointless extra layer of complexity anyway.

It's a matter of using the best tool for each particular job, not just sticking with one. My own ~/bin directory has a big mix of Perl and pure shell, depending on the complexity of the job to be done.

crb3 2 points · 8 days ago · edited 7 days ago

Agreed; I brought that example up to illustrate the bulk issue. In it, I was feeling my way, not sure how much finagling I might have to do for the task (backdoor-passing legitimate sparse but possibly quite bulky email from one server to another), which is why I initially went for the pure-Perl approach, so I'd have the mechanics exposed for any needed hackery. The experience taught me to get by more on shelling to precompiled tooling where appropriate... and a healthy respect for CPAN pull-in, [e:] the way that this module depends on that module so it gets pulled in along with its dependencies in turn, and the pileup grows in memory. There was a time or two here and there where I only needed a teeny bit of what a module does, so I went in and studied the code, then implemented it internally as a function without the object's generalities and bulk. The caution learned on ancient x86 boxes now seems appropriate on ARM boards like rPi; what goes around comes around.

minimim 1 point · 4 days ago

wouldn't have steered people away from perfectly usable Perl5

Perl5 development was completely stalled at the time. Perl6 brought not only new blood into it's own effort, it reinvigorated Perl5 in the process.

It's completely backwards to suggest Perl 5 was fine until perl6 came along. It was almost dormant and became a lively language after Perl 6 was announced.

perlancar 2 points · 8 days ago

I don't observe the premise at all though. Is bash really gaining ground over anything recently? l

linearblade 3 points · 8 days ago

Perl is better than pretty much everything g out there at what it does.

But keep in mind,

They say C sharp is loved by everyone, when in reality it's Microsoft pushing their narrative and the army of "learn by rote" engineers In developing countries

Python again is loved, because "taught by rote" idiots. Now you can give them pretty little packages. And it's no wonder they can do little better than be glorified system admins (which id rather have a real sys admin, since he's likely to understand Perl)

Making a new language means lots of new training. Lots of profit in this. Nobody profits from writing new books on old languages. Lots of profit in general from supporting a new language. In the end, owning the language gets you profits.

And I still don't get why tab for blocks python is even remotely more readable than Perl.

If anything, JavaScript is pretty dang godly at what it does, I understand why that's popular. But I don't get python one bit, except to employ millions of entry level minions who can't think on their own.

duo-rotae 6 points · 8 days ago

I know a comp sci professor. I asked why he thought Python was so popular.

"Every teacher I know has students using it. We do it because it's an easy language, there's only one way to do it, and with whitespace as syntax it's easy to grade. We don't teach it because it is some powerful or exceptional language. "

Then he said if he really needs to get something done, it's Perl or C.

linearblade 2 points · 8 days ago

Yep that's pretty much my opinion from using it.

techsnapp 1 point · 2 days ago

So is per harder than python because the lack of everyone else using it?

duo-rotae 1 point · 2 days ago

Perl has a steeper and longer learning with it. curve than Python, and there is more than one way to do anything. And there quite a few that continue coding

[Sep 19, 2019] Min and max functions in Perl by Tim

Feb 01, 2012 | timmurphy.org

Posted: 1st February 2012 by Tim in Perl

Tags: list , math , max , min , Perl , script 3

Min and max functions are available in perl, but you need to load them first. To do this, add

use List::Util qw[min max];

to the top of the script. These functions take a list of numbers and return the min/max of that list. The list can have 2 numbers or 100 – it doesn't matter:

use List::Util qw[min max];

print min(1,3) . "\n";
print max(1,2,3,4,5) . "\n";
print min(1) . "\n";

[Sep 19, 2019] Luke's Thought Dump Cute Perl Gem to Get the Minimum-Maximum Value

Notable quotes:
"... the comparison operators return 1 or 0 for true and false, respectively, which are then used by this code to index the array ref. ..."
Sep 19, 2019 | lukesthoughtdump.blogspot.com

Sunday, August 2, 2009 Cute Perl Gem to Get the Minimum/Maximum Value Saw this little nugget on #perl@irc.perl.org the other night. It determines the minimum of two values:

[$b, $a]->[$a <= $b]
It takes advantage of the fact that Perl doesn't have a Boolean return type for true or false, so the comparison operators return 1 or 0 for true and false, respectively, which are then used by this code to index the array ref.

To get the maximum of the two values, just flip the operator to >= Posted by Luke at

Labels: hacks , perl

[Sep 19, 2019] List::MoreUtils's minmax is more efficient when you need both the min and the max (because it does fewer comparisons).

Notable quotes:
"... List::MoreUtils's minmax is more efficient when you need both the min and the max (because it does fewer comparisons). ..."
Sep 19, 2019 | stackoverflow.com

List::Util's min and max are fine,

use List::Util qw( min max );
my $min = min @numbers;
my $max = max @numbers;

But List::MoreUtils's minmax is more efficient when you need both the min and the max (because it does fewer comparisons).

use List::MoreUtils qw( minmax );
my ($min, $max) = minmax @numbers;

List::Util is part of core, but List::MoreUtils isn't.

--ikegami

[Sep 16, 2019] Perl For Dummies Cheat Sheet

Sep 16, 2019 | www.dummies.com

From Perl For Dummies, 4th Edition

By Paul Hoffman

Perl enables you to write powerful programs right from the start, whether you're a programming novice or expert. Perl offers the standard programming tools -- comparison operators, pattern-matching quantifiers, list functions -- and has shortcuts for inputting character ranges. Perl also offers file tests so you can find what you want fast.

The Most Useful File Tests in Perl

Programming with Perl is fairly straightforward, which runs to the letters you use for file tests. For example, r tests whether a file can be r ead, and T looks for a t ext file. Here are most useful file tests in Perl:

Test Description
-e File exists.
-r File can be read.
-w File can be written to.
-z File is exactly zero bytes long.
-d Named item is a directory, not a file.
-T File is a text file. (The first chunk of a file is examined,
and it's a text file if fewer than 30 percent or so of the
characters are nonprintable.)
-B File is a binary file. (This is the exact opposite of the -T
test -- it's a binary file if more than 30 percent or so
of the characters are nonprintable.)
-s Size of the file in bytes.
-C Creation age of file.
-A Access age of file.
-M Modification age of file.
Special Characters in Perl

Like any programming language, Perl uses special commands for special characters, such as backspaces or vertical tabs. So, if you need to program in a bell or a beep or just a carriage return, check the following table for the character that will produce it:

Character Meaning
n Newline
r Carriage return
t Tab character
f Formfeed character
b Backspace character
v Vertical tab
a Bell or beep
e Escape character
Perl True-False Comparison Operators

When you're programming with Perl -- or any other language -- you use comparison operators all the time. The following table shows the common comparisons for Perl in both math and string form:

Comparison Math String
Equal to == eq
Not equal to != ne
Less than < lt
Greater than > gt
Less than or equal to <= le
Greater than or equal to >= ge
Common List Functions in Perl

Perl was originally designed to help process reports more easily. Reports often contain lists, and you may want to use Perl to perform certain functions within a list. The following table shows you common list functions, their splice equivalents, and explains what the function does:

Function splice Equivalent What It Does
push (@r, @s) splice(@r, $#r+1,0, @s) Adds to the right of the list
pop (@r) splice(@r, $#r, 1) Removes from the right of the list
shift (@r) splice(@r, 0, 1) Removes from the left of the list
unshift (@r, @s) splice(@r, 0, 0,@s) Adds to the left of the list
Shortcuts for Character Ranges in Perl

You're programming along in Perl and want to use a code shortcut to represent anything from a number to a non-number to any letter or number. You're in luck, because the following table gives you the code, shows you what it's a shortcut for, and describes it.

Code Replaces Description
d [0..9] Any digit
w [a-zA-Z_0-9] Any alphanumeric character
s [ tnrf] A whitespace character
D ^[0..9] Any non-digit
W ^[a-zA-Z_0-9] Any non-alphanumeric character
S ^[ tnrf] A non-whitespace character
Perl Pattern-Matching Quantifiers

Perl enables you to use common symbols to instruct the program you're writing to match data once, never, or up to a certain number of times. The following table shows you which symbol to use to get the match you want:

Symbol Meaning
+ Match 1 or more times
* Match 0 or more times
? Match 0 or 1 time
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n, but not more than m, times (these values must
be less than 65,536)

[Sep 16, 2019] How can I capture multiple matches from the same Perl regex - Stack Overflow

Sep 16, 2019 | stackoverflow.com

How can I capture multiple matches from the same Perl regex? Ask Question Asked 9 years, 4 months ago Active 7 years, 4 months ago Viewed 35k times 24 1


brian d foy ,May 22, 2010 at 15:42

I'm trying to parse a single string and get multiple chunks of data out from the same string with the same regex conditions. I'm parsing a single HTML doc that is static (For an undisclosed reason, I can't use an HTML parser to do the job.) I have an expression that looks like:
$string =~ /\<img\ssrc\="(.*)"/;

and I want to get the value of $1. However, in the one string, there are many img tags like this, so I need something like an array returned (@1?) is this possible?

VolatileRig ,Jan 14, 2014 at 19:41

As Jim's answer, use the /g modifier (in list context or in a loop).

But beware of greediness, you dont want the .* to match more than necessary (and dont escape < = , they are not special).

while($string =~ /<img\s+src="(.*?)"/g ) {
  ...
}

Robert Wohlfarth ,May 21, 2010 at 18:44

@list = ($string =~ m/\<img\ssrc\="(.*)"/g);

The g modifier matches all occurences in the string. List context returns all of the matches. See the m// operator in perlop .

dalton ,May 21, 2010 at 18:42

You just need the global modifier /g at the end of the match. Then loop through until there are no matches remaining
my @matches;
while ($string =~ /\<img\ssrc\="(.*)"/g) {
        push(@matches, $1);
}

VolatileRig ,May 24, 2010 at 16:37

Use the /g modifier and list context on the left, as in
@result = $string =~ /\<img\ssrc\="(.*)"/g;

[Sep 16, 2019] https://www.dummies.com/programming/perl/avoiding-common-oversights-in-perl/

Sep 16, 2019 | www.dummies.com

Avoiding Common Oversights in Perl

Related Book

Perl For Dummies, 4th Edition

By Paul Hoffman

Entering a typo or two during the course of writing a Perl program is not uncommon. But when you attempt to run a program containing a text-entry slip-up, Perl usually becomes confused and tells you so by reporting an error. The natural reaction for most people, even those with years of programming experience, is to get worried or angry or both when an error message pops up.

Don't panic. Take a deep breath. Take another slow, deep breath. Seriously, you can't get to the root of the problem if you're all tense and bothered. No matter how many years you program, you always end up finding some errors in the code you're written.

So, now that you are (hopefully!) a bit calmer, you can start to appreciate the fact that Perl has more helpful error messages than almost any other programming language. The messages aren't always right on the money, but they can get you pretty close to the spot where the problem lies with minimal searching on your part.

Perl has myriad error messages, but a few definitely crop up more than others owing to some common typos that everyone seems to make. The following errors result from minor text-entry goofs that you can easily avoid.

Forgetting a semicolon

Probably the most common error message you see when programming in Perl looks something like this:

# syntax error, near "open"
File 'counter1.pl'; Line 10
# Execution aborted due to compilation errors.

You can look and look at Line 10, the one with the open statement, and you won't see anything wrong with it. The trick here is to examine the statement that comes before the open statement and see whether it ends with a semicolon. (Perl knows that a statement ends only when it encounters a semicolon.) In this case, the error is caused by a missing semicolon at the end of Line 7 of the program:

$TheFile = "sample.txt"

Forgetting a quotation mark

The following sort of error message can be extremely frustrating if you don't know of a quick fix:

# Bare word found where operator expected, near
# "open(INFILE, $TheFile) or die "The"
# (Might be a runaway multi-line " string starting on
# line 7)
File 'counter1.pl'; Line 10

This error is similar to forgetting a semicolon; instead, it's a quotation mark that's accidentally omitted:

$TheFile = "sample.txt;

In this case, Perl did a good job of guessing what is wrong, suggesting that a runaway multi-line " string on Line 7 is the problem, which is precisely right.

Entering one parenthesis too many or too few

When you have loads of opening and closing parentheses in a program, it's easy to slip an extra one in by accident. If that's the case, you may see a message from Perl that reads something like this:

# syntax error, near ") eq"
File 'counter1.pl'; Line 38
# syntax error, near "}"
File 'counter1.pl'; Line 42

Here, Perl can't determine where the error is exactly, but it actually got it right on the first guess: Line 38 contains an extra right parenthesis:

if(substr($TheLine, $CharPos, 1)) eq " ")

Having one parenthesis too few in a Perl program can cause harder-to-find problems:

# Can't use constant item as left arg of implicit -- >,
# near "1 }"
File 'counter1.pl'; Line 39
# Scalar found where operator expected, near "$CharPos"
File 'counter1.pl'; Line 40
# (Missing semicolon on previous line?)
# syntax error, near "$CharPos "
File 'counter1.pl'; Line 40

Yarp! All this was produced because the last parenthesis on Line 38 is missing:

if(substr($TheLine, $CharPos, 1) eq " "

Here is another good lesson in hunting down typing errors: Start where Perl says it found an error. If you don't find the error there, go up a line or two and see if the problem started earlier.

A final word of advice: Trust Perl to find the simple typos for you (where it can), and remember that it's giving you all the help it can, which is more than you can say for many programming languages.

[Sep 16, 2019] Switch Statements

Sep 16, 2019 | perldoc.perl.org

Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you can say

  1. use feature "switch" ;

to enable an experimental switch feature. This is loosely based on an old version of a Perl 6 proposal, but it no longer resembles the Perl 6 construct. You also get the switch feature whenever you declare that your code prefers to run under a version of Perl that is 5.10 or later. For example:

  1. use v5.14 ;

Under the "switch" feature, Perl gains the experimental keywords given , when , default , continue , and break . Starting from Perl 5.16, one can prefix the switch keywords with CORE:: to access the feature without a use feature statement. The keywords given and when are analogous to switch and case in other languages -- though continue is not -- so the code in the previous section could be rewritten as

  1. use v5.10.1 ;
  2. for ( $var ) {
  3. when ( /^abc/ ) { $abc = 1 }
  4. when ( /^def/ ) { $def = 1 }
  5. when ( /^xyz/ ) { $xyz = 1 }
  6. default { $nothing = 1 }
  7. }

The foreach is the non-experimental way to set a topicalizer. If you wish to use the highly experimental given , that could be written like this:

  1. use v5.10.1 ;
  2. given ( $var ) {
  3. when ( /^abc/ ) { $abc = 1 }
  4. when ( /^def/ ) { $def = 1 }
  5. when ( /^xyz/ ) { $xyz = 1 }
  6. default { $nothing = 1 }
  7. }

As of 5.14, that can also be written this way:

  1. use v5.14 ;
  2. for ( $var ) {
  3. $abc = 1 when /^abc/ ;
  4. $def = 1 when /^def/ ;
  5. $xyz = 1 when /^xyz/ ;
  6. default { $nothing = 1 }
  7. }

Or if you don't care to play it safe, like this:

  1. use v5.14 ;
  2. given ( $var ) {
  3. $abc = 1 when /^abc/ ;
  4. $def = 1 when /^def/ ;
  5. $xyz = 1 when /^xyz/ ;
  6. default { $nothing = 1 }
  7. }

The arguments to given and when are in scalar context, and given assigns the $_ variable its topic value.

Exactly what the EXPR argument to when does is hard to describe precisely, but in general, it tries to guess what you want done. Sometimes it is interpreted as $_ ~~ EXPR , and sometimes it is not. It also behaves differently when lexically enclosed by a given block than it does when dynamically enclosed by a foreach loop. The rules are far too difficult to understand to be described here. See Experimental Details on given and when later on.

Due to an unfortunate bug in how given was implemented between Perl 5.10 and 5.16, under those implementations the version of $_ governed by given is merely a lexically scoped copy of the original, not a dynamically scoped alias to the original, as it would be if it were a foreach or under both the original and the current Perl 6 language specification. This bug was fixed in Perl 5.18 (and lexicalized $_ itself was removed in Perl 5.24).

If your code still needs to run on older versions, stick to foreach for your topicalizer and you will be less unhappy.

[Sep 12, 2019] Why is Perl no longer a popular programming language - Quora

May 19, 2019 | www.quora.com
  1. die " Reports of my death are greatly exaggerated . \n "

Perl is alive and well, but it has steadily been losing promise over the past 20 years.

It's still heavily used for the tasks it was used for when I learnt it, in 1994–1995, but at that time, it looked set for an even brighter future: it was developing into one of the top-5 languages, a universal scripting language, a language you expect to find wherever scripting or dynamically typed languages are appropriate.

You can still find evidence of that today: some software has an extension API in Perl, some web applications are written in Perl, some larger system administration software is written in Perl, etcetera. But these systems are typically 20 years old. If you do this today, be prepared to justify yourself.

This is not because Perl has become any less suitable for doing these things. On the contrary, it has continued to improve. Yet, people have turned away from Perl, towards newer scripting languages such as Python, PHP, Ruby, and Lua, for tasks that in 1995 they would probably have used Perl for.

Why?

I believe the reason is simple: Perl is very free, syntactically and semantically. This makes it very good at what it was designed to do (scripting) but less suited for larger-scale programming.

Perl's syntactic freedom mostly originates from its mimicking idioms from other languages. It was designed to be a suitable replacement for other scripting languages, most notably the Bourne shell ( /bin/ sh ) and awk , so it adopts some of their idioms. This is perfect if you like these idioms for their compactness.

For instance, in the Bourne shell, we can write

  1. if mkdir $directory
  2. then
  3. echo successfully created directory : $directory
  4. elif test - d $directory
  5. then
  6. echo pre - existing directory : $directory
  7. else
  8. echo cannot create directory : $directory
  9. fi

In the Bourne shell, every statement is a Unix command invocation; in this case, test and mkdir . (Some commands, such as test , were built into the shell later.) Every command will succeed or fail, so we can use it in the condition of an if statement.

Now what if we only want to print a warning when something went wrong? We can write this:

  1. if mkdir $directory
  2. then
  3. : # nothing
  4. elif test - d $directory
  5. then
  6. : # nothing
  7. else
  8. echo cannot create directory : $directory
  9. fi

or we can combine the two conditions:

  1. if mkdir $directory || test - d $directory
  2. then
  3. : # nothing
  4. else
  5. echo cannot create directory : $directory
  6. fi

or we can combine them even further:

  1. mkdir $directory ||
  2. test - d $directory ||
  3. echo cannot create directory : $directory

These all do the same exact thing; clearly, the last version is the most compact. In a shell script with a lot of tests like this, writing things this way can save a considerable amount of space. Especially in throwaway scripts of a few lines, it's a lot easier to use more compact syntax.

Most programmers are familiar with seeing some special syntax for conditions in if statements. For this reason, Unix has the [ command, which scans its arguments for a matching ], and then invokes test with the arguments up to that point. So we can always replace

  1. test - d $directory

with

  1. [ - d $directory ]

in the pieces of code above. It means the same thing.

Now, Perl comes onto the scene. It is designed to be easy to replace Bourne shell scripts with. This is a very frequent use case for Perl, even today: I regularly find myself rewriting my Bourne shell scripts into Perl by going through them line by line.

So what do the Perl replacements of the above look like?

Here we go:

  1. if ( mkdir $directory )
  2. {
  3. # nothing
  4. } elsif (- d $directory )
  5. {
  6. # nothing
  7. } else {
  8. say "cannot create directory: $directory"
  9. }

or we can combine the two conditions:

  1. if ( mkdir $directory || - d $directory )
  2. {
  3. # nothing
  4. } else {
  5. say "cannot create directory: $directory"
  6. }

or we can combine them even further:

  1. mkdir $directory or
  2. - d $directory or
  3. say "cannot create directory: $directory"

As you can see, these are literal transliterations of the corresponding Bourne shell fragments.

In a language such as Java, you can use the first two forms, but not the third one. In such languages, there is a syntactic separation between expressions , which yield a value, and must be used in a context that demands such a value, and statements , which do not yield a value, and must be used in contexts that do not demand one. The third form is syntactically an expression, used in a context that demands a statement, which is invalid in such a language.

No such distinction is made in Perl, a trait it inherited from the Bourne shell, which in turn took it from Algol 68.

So here we have an example of syntactic freedom in Perl that many other languages lack, and in this case, Perl took it from the Bourne shell.

Allowing more compactness isn't the only reason for this freedom. The direct reason the Bourne shell doesn't make the distinction is that it relies on Unix commands, which do not make the distinction, either. Every Unix command can return a value (a return code) to indicate whether it failed and how. Therefore, it acts both as a statement and as a condition. There is a deeper reason behind this: concurrency.

For instance, when we want to create a directory, we can't separate doing it from testing whether it can/could be done. We could try and write something like

  1. if ( some test to see if we can mkdir $directory )
  2. then
  3. mkdir directory
  4. fi
  5. if ( some test to see if we managed to mkdir directory )
  6. then
  7. [...]
  8. fi

but that logic isn't correct. Unix is a multiprogramming environment, so anything could happen between our first test and our mkdir command, and before our mkdir command and the second test. Someone else might create that directory or remove it, or do something else that causes problems. Therefore, the only correct way to write code that tries to create a directory and determines whether it succeeds is to actually issue the mkdir command and check the value it returned. Which is what the constructs above do.

A shortcut like

  1. mkdir $directory or
  2. - d $directory or
  3. say "cannot create directory: $directory"

is just a consequence. Of course, you can still object to using it for stylistic reasons, but at least the construct makes sense once you know its origins.

Programmers who are unfamiliar with the paradigm of mixing statements and expressions, who have never seen any but the simplest of Bourne shell scripts, who have only been given programming tasks in which their program calls all the shots and nothing else can interfere, have never encountered a reason to treat statements and expressions as the same thing. They will be taken aback by a construct like this. I can't read this , they will mutter, it's incomprehensible gibberish . And if Perl is the first language they've seen that allows it, they will blame Perl. Only because they were never subjected to a large amount of Bourne shell scripting. Once you can read that, you can read anything ; Perl will look pretty tame in comparison.

Similar reasons can be given for most of the other syntactical freedom in Perl. I must say, Perl sometimes seems to make a point of being quirky, and I find some of the resulting oddities hard to justify, but they do make sense in context. The overall motivation is compactness. In scripting, where you type a lot and throw away a lot, the ability to write compact code is a great virtue.

Due to these syntactic quirks, Perl got a reputation for being a write-only language - meaning that when programmer A is faced with programmer B 's code, B may have used all kinds of idioms that A is unfamiliar with, causing delays for A . There is some truth to this, but the problem is exaggerated: syntax is the first thing you notice about a program, which is why it sticks out, but it's pretty superficial: new syntax really isn't so hard to learn.

So I'm not really convinced Perl's syntactic freedom is such a bad thing, except that people tend to blow it out of proportion.

However, Perl is also very free semantically : it is a truly dynamic language, allowing programmers to do all kinds of things that stricter languages forbid. For instance, I can monkey-patch functions and methods in arbitrary code that I'm using. This can make it very hard for programmers to understand how a piece of code is working, or whether it is working as intended.

This becomes more important when a software system grows larger or when others than the original author start to rely on it. The code doesn't just need to work, but it must be understandable to others. Consequently, in large, stable code bases, compactness and freedom of expression are less important than consistency, a smooth learning curve for beginners, and protection against routine errors. Therefore, many software development teams prefer languages such as Java, with its very limited syntactic freedom and strict compile-time type checking. Perl is at the opposite end of the spectrum, with its extreme syntactic and semantic freedom.

This wouldn't be a problem if there were ways to straitjacket Perl if you wanted to; if there was a way to say: for this project, be as rigid as Java syntactically or semantically; I want as few surprises as possible in code that I didn't write. Sure enough, Perl has support for compile-time checking ( use strict ; use warnings , and the perlcritic utility) and consistent code formatting (the perltidy utility), but they were added as afterthoughts and cannot come anywhere near the level of strictness a Java programmer would expect.

To support that, the language needed to be redesigned from scratch, and the result would be incompatible with the original. This effort has been made, producing Perl 6, but in the meantime, many other languages sprung up and became popular for the cases Perl programmers wanted to use Perl for, and if you're going to switch to an incompatible language anyway, why not use one of those instead?

[Sep 12, 2019] CMOS #12- Randal Schwartz the host of FLOSS Weekly

The fate of Perl 6 is unclear but Perl 5.10 is here to stay. Some thing were screwed after Perl 5.10, but they might be eventually corrected. OO-enthusiasts did a every bad service to Perl trying to enforce unsuitable for programming, say, utilities paradigm on everybody. That led to huge inefficiencies and bloated difficult to maintain code. That also somewhat devalued Perl standard library as the conversion to OO spoiled the broth.
Notable quotes:
"... I'm keeping up with Perl, but not really, I still see a feature, like in Perl 5.16, and I go, Oh, that's in relatively modern Perl, no wonder I don't know about it. I think of Perl as whatever was back in 5.10 and 5.12, that's the latest that I was writing my books for, my trainings for. ..."
"... So the stuff that's coming out in 5.18 and 5.20 and 5.22 now, is sort of beyond me, I just can't keep up with Perl-delta, and that's a scary thing for the number one prolific author about Perl, to not be able to keep up with what's happening in the Perl community, this is clearly an indication that Perl is alive and well, and I've kind of missed the boat, now. ..."
"... And every time I go to YAPC or some other place where they're talking about Perl 6, I get excited about it, for all of a month, and then I come back and then I go, How am I going to use this practically? None of my current clients are demanding that. ..."
Sep 12, 2019 | code-maven.com

09:24 Randal Schwartz

Yeah, I think a few years ago, it was all about cloud stuff. So it was all about running your application in cloud. Starting probably a couple years ago, with the Docker revolution, it's all about containers now.

But we're also seeing a revolution in smart, JavaScript-based ultimately, front-ends, that are doing things like single-page applications and stuff, and I'm really pretty excited about that. Not that I ever really wanted to spend a lot of time playing with JavaScript, but unfortunately I guess that that's a requirement, so I'm continuing to hone my JavaScript skills.

I'm also honing my Dart skills, because that language out of Google, is really gaining some traction, in terms of being able to do server-side stuff, essentially replacing Node.JS with a reasonable language. And also client-side stuff for all the modern browsers, and it translating down into JavaScript, so as long as there's a reasonable ECMA 5 or something available in the browser, Dart works really nicely. But Dart looks closer, as a language, to something like Java, with optional typing, so if you add types to variables, you can actually get hints from your development environment and that's pretty slick. So I'm learning Dart in the background, I actually have a couple applications for it already, that as I learn more, I'll be able to deploy. I'm also learning things like Angular , so I can have reactive front-ends, and again, it's like there's not enough hours in the day for me to learn everything I want to learn.

I'm keeping up with Perl, but not really, I still see a feature, like in Perl 5.16, and I go, Oh, that's in relatively modern Perl, no wonder I don't know about it. I think of Perl as whatever was back in 5.10 and 5.12, that's the latest that I was writing my books for, my trainings for.

So the stuff that's coming out in 5.18 and 5.20 and 5.22 now, is sort of beyond me, I just can't keep up with Perl-delta, and that's a scary thing for the number one prolific author about Perl, to not be able to keep up with what's happening in the Perl community, this is clearly an indication that Perl is alive and well, and I've kind of missed the boat, now.

17:53 Gabor Szabo Yeah, so as a closing question, I would like to go back a little bit to the languages and the things you do with open source, and ask you, where are you heading? Are you going to go back to Perl and learn what the new things in Perl are, or are you more interested in other languages, and which ones?

18:16 Randal Schwartz

Well, I download and compile Perl 6 every day. And every time I go to YAPC or some other place where they're talking about Perl 6, I get excited about it, for all of a month, and then I come back and then I go, How am I going to use this practically? None of my current clients are demanding that.

Clearly if I were to write training materials for that, I'd have to present it at least to 200 people, whether that's 10 classes of 20, or a giant 200 person week-end event, that's sort of the minimum for amortizing the inception cost for any class that I've ever written. So I use the 200 number as kind of a rule of thumb.

And I just don't see that happening, I don't see getting enough people together in the right places, to be able to do that. So I continue to watch what people are doing with Perl 6, I continue compiling it every day, and I'd love for it to become extremely popular so I could go back to that, and say I could continue my Perl heritage.

But, as I mentioned earlier, I think Dart has legs. Given that Google's behind it, given that Google and a number of other companies are already deploying public-facing projects in it. Given that it does compile down and work in all modern browsers, I easily see the need for like rent a hotel room for a weekend and have 20, 50, 100 people show up to learn about it, because single-page applications are all the rage right now, and Dart is a really solid language for that, and Google is betting on that.

You may say, Where is Go in that equation? Go is great for server-side stuff, and great for the kind of things they're doing on back-ends, and although Dart can also do back-end stuff, essentially replacing Node.JS for that sort of thing, and have a single language for both back-end and front-end. Dart's real win is in the front-end, being able to be transpiled over to JavaScript and being able to scale to hundreds of thousands of lines of code for some of their larger applications. I think that's got legs, I'm in on the groundfloor, like I was on Perl, I'm already recognized among the Dart people as being someone who can put things together. I did a one-hour long intro to Dart talk that was reviewed by some of the key people in the Dart community, and they really like what I did with it, so I seem to have, again, that knack for finding something complex and finding the simplest ends of it, and I'm already there with Dart.

And also, the whole Fuchsia announcement a few weeks ago, where Google's coming out with this language for real-time operating systems, and it has a strong Dart component in it. I think that's another thing that says, say if they start putting that in Google Glass , or if they even put that as a replacement for the Android operating system, or for Google Chrome, which some people are suspecting that this is all amalgamation of it.

Especially when somebody's looking at the source code the other day, and it has a lot of files, not only from Android, but also from the old Be OS , which was sort of the predecessor of what eventually became OS X, kind of interesting that that's part of that project as well.

So with Fuchsia on the horizon, with Dart already being deployed by numbers of people, with me having a knack for understanding how Dart actually works, given that it was also built by some of the key players in Smalltalk, which I go back 16 years with, I think this is probably the right place for me to look at my future.

22:02 Gabor Szabo And I guess, FLOSS Weekly?

22:05 Randal Schwartz

FLOSS Weekly will continue.

In fact I just had a converstaion recently with Leo, we're one of the smaller shows on the network, but he's absolutely committed to this show. He likes what I'm doing with it, he likes the directions I'm taking it, he likes the team I've put together, who were able to pick up the show, even when I was absent for six weeks, in the hospital recently, without notice unfortunately, I guess that's always the way you end up in the hospital.

So my team picked up, and Aaron Newcomb did a great job of hosting while I was gone, but Leo likes the team I've built and Leo likes the kinds of guests I'm getting on, the variety especially. I've had a lot of people write in and say, I don't always want or understand the thing you're talking about, but I listen to the way you interview them, and I listen to the things you're able to pull out, like what's the governance model, how are you making money with this, what got you started? These sorts of things are really sort of cross-project. You know, you can learn that sort of stuff about anything you want to start, and like I said, I learned a lot already by doing this show and so a lot of the audience is picking that up. And we have a fun time.

I tell jokes sometimes and I have a bad way of making really bad puns. And that's kind of the way it works but I really enjoy the show, I'm going to keep doing it. And I told Leo I would just keep doing this as long as he let's me, and he goes, Well then, that makes two of us. So we'll still be doing this in 20 years, if they let us. And I said, That sounds like a great promise, Leo, thank you. So yeah, I'll be doing FLOSS Weekly for at least awhile longer.

23:45 Gabor Szabo I'm happy to hear that and I hope to see a lot more of that. And I hope to see you somewhere, I don't know, maybe at a Dart conference?

23:56 Randal Schwartz

Yeah, that'd be awesome!

And I think you come to OSCon , occasionally, or maybe, well I've got to get out to a YAPC::Europe or a YAPC::Israel or something at some point, but just haven't made those yet. I think it's partially because I need to figure out what to pitch to the Perl conference.

Oh wait, I could just be press again! That's the other thing, is that FLOSS Weekly has allowed me to apply as press for OSCon for the last few years, even though I don't have an actual talk to give. And Red Hat actually invited me to their conference, as press. And I thought, Well, that's the first time that's happened. That really says I've made it. That really says that FLOSS Weekly is recognized as legitimate press. So I'm wearing a whole 'nother hat, so my hat tree of all my hats, hanging up in the corner, has gotten a whole 'nother rung.

[Sep 12, 2019] prename -- rename files using any perl expressior (regex, tr, etc)

Sep 12, 2019 | gist.githubusercontent.com
#!/usr/bin/perl -w
#
#  This script was developed by Robin Barker (Robin.Barker@npl.co.uk),
#  from Larry Wall's original script eg/rename from the perl source.
#
#  This script is free software; you can redistribute it and/or modify it
#  under the same terms as Perl itself.
#
# Larry(?)'s RCS header:
#  RCSfile: rename,v   Revision: 4.1   Date: 92/08/07 17:20:30 
#
# $RCSfile: rename,v $$Revision: 1.5 $$Date: 1998/12/18 16:16:31 $
#
# $Log: rename,v $
# Revision 1.5  1998/12/18 16:16:31  rmb1
# moved to perl/source
# changed man documentation to POD
#
# Revision 1.4  1997/02/27  17:19:26  rmb1
# corrected usage string
#
# Revision 1.3  1997/02/27  16:39:07  rmb1
# added -v
#
# Revision 1.2  1997/02/27  16:15:40  rmb1
# *** empty log message ***
#
# Revision 1.1  1997/02/27  15:48:51  rmb1
# Initial revision
#

use strict;

use Getopt::Long;
Getopt::Long::Configure('bundling');

my ($verbose, $no_act, $force, $op);

die "Usage: rename [-v] [-n] [-f] perlexpr [filenames]\n"
    unless GetOptions(
        'v|verbose' => \$verbose,
        'n|no-act'  => \$no_act,
        'f|force'   => \$force,
    ) and $op = shift;

$verbose++ if $no_act;

if (!@ARGV) {
    print "reading filenames from STDIN\n" if $verbose;
    @ARGV = ;
    chop(@ARGV);
}

for (@ARGV) {
    my $was = $_;
    eval $op;
    die $@ if $@;
    next if $was eq $_; # ignore quietly
    if (-e $_ and !$force)
    {
        warn  "$was not renamed: $_ already exists\n";
    }
    elsif ($no_act or rename $was, $_)
    {
        print "$was renamed as $_\n" if $verbose;
    }
    else
    {
        warn  "Can't rename $was $_: $!\n";
    }
}

__END__

=head1 NAME

rename - renames multiple files

=head1 SYNOPSIS

B S ]> S ]> S ]> I S ]>

=head1 DESCRIPTION

C
renames the filenames supplied according to the rule specified as the
first argument.
The I 
argument is a Perl expression which is expected to modify the C
string in Perl for at least some of the filenames specified.
If a given filename is not modified by the expression, it will not be
renamed.
If no filenames are given on the command line, filenames will be read
via standard input.

For example, to rename all files matching C to strip the extension,
you might say

        rename 's/\.bak$//' *.bak

To translate uppercase names to lower, you'd use

        rename 'y/A-Z/a-z/' *

=head1 OPTIONS

=over 8

=item B, B

Verbose: print names of files successfully renamed.

=item B, B

No Action: show what files would have been renamed.

=item B, B

Force: overwrite existing files.

=back

=head1 ENVIRONMENT

No environment variables are used.

=head1 AUTHOR

Larry Wall

=head1 SEE ALSO

mv(1), perl(1)

=head1 DIAGNOSTICS

If you give an invalid Perl expression you'll get a syntax error.

=head1 BUGS

The original C did not check for the existence of target filenames,
so had to be used with care.  I hope I've fixed that (Robin Barker).

=cut



[Sep 10, 2019] Perl Modules and namespaces

javatpoint

A module is a container which holds a group of variables and subroutines which can be used in a program. Every module has a public interface, a set of functions and variables.

To use a module into your program, require or use statement can be used, although their semantics are slightly different.

The 'require' statement loads module at runtime to avoid redundant loading of module. The 'use' statement is like require with two added properties, compile time loading and automatic importing.

Namespace is a container of a distinct set of identifiers (variables, functions). A namespace would be like name::variable .

Every piece of Perl code is in a namespace.

In the following code,

  1. use strict;
  2. use warnings;
  3. my $x = "Hello" ;
  4. $main ::x = "Bye" ;
  5. print "$main::x\n" ; # Bye
  6. print "$x\n" ; # Hello

Here are two different variables defined as x . the $main::x is a package variable and $x is a lexical variable. Mostly we use lexical variable declared with my keyword and use namespace to separate functions.

In the above code, if we won't use use strict , we'll get a warning message as

  1. Name "main::x" used only once: possible typo at line..

The main is the namespace of the current script and of current variable. We have not written anything and yet we are already in the 'main' namespace.

By adding 'use strict', now we got the following error,

  1. Global symbol "$x" requires explicit package name

In this error, we got a new word 'package'. It indicates that we forgot to use 'my' keyword before declaring variable but actually it indicates that we should provide name of the package the variable resides in.


Perl Switching namespace using package keyword

Look at the following code,

  1. use strict;
  2. use warnings;
  3. use 5.010;
  4. sub hii {
  5. return "main" ;
  6. }
  7. package two;
  8. sub hii {
  9. return "two" ;
  10. }
  11. say main::hii(); # main
  12. say two::hii(); # two
  13. say hii(); # two
  14. package main;
  15. say main::hii(); # main
  16. say two::hii(); # two
  17. say hii(); # main

Here we are using package keyword to switch from 'main' namespace to 'two' namespace.

Calling hii() with namespaces returns respective namespaces. Like , say main::hii(); returns 'main' and say two::hii(); returns 'two'.

Calling hii() without namespace prefix, returns the function that was local to the current namespace. In first time, we were in 'two' namespace. Hence it returned 'two'. In second time, we switched the namespace using package main. Hence it returns 'main'.

[Sep 10, 2019] Use of uninitialized value

Sep 10, 2019 | perlmaven.com

Prev Next This is one of the most common warning you will encounter while running Perl code.

It is a warning, it won't stop your script from running and it is only generated if warnings were turned on. Which is recommended.

The most common way to turn on warnings is by including a use warnings; statement at the beginning of your script or module.

Are you serious about Perl? Check out my Beginner Perl Maven book .
I have written it for you!

The older way is adding a -w flag on the sh-bang line. Usually looks like this as the first line of your script:

#!/usr/bin/perl -w

There are certain differences, but as use warnings is available for 12 years now, there is no reason to avoid it. In other words:

Always use warnings; !

Let's go back to the actual warning I wanted to explain.

A quick explanation
Use of uninitialized value $x in say at perl_warning_1.pl line 6.

This means the variable $x has no value (its value is the special value undef ). Either it never got a value, or at some point undef was assigned to it.

You should look for the places where the variable got the last assignment, or you should try to understand why that piece of code has never been executed.

A simple example

The following example will generate such warning.

  1. use warnings ;
  2. use strict ;
  3. use 5.010 ;
  4. my $x ;
  5. say $x ;

Perl is very nice, tells us which file generated the warning and on which line.

Only a warning

As I mentioned this is only a warning. If the script has more statements after that say statement, they will be executed:

  1. use warnings ;
  2. use strict ;
  3. use 5.010 ;
  4. my $x ;
  5. say $x ;
  6. $x = 42 ;
  7. say $x ;

This will print

Use of uninitialized value $x in say at perl_warning_1.pl line 6.

42
Confusing output order

Beware though, if your code has print statements before the line generating the warning, like in this example:

  1. use warnings ;
  2. use strict ;
  3. use 5.010 ;
  4. print 'OK' ;
  5. my $x ;
  6. say $x ;
  7. $x = 42 ;
  8. say $x ;

the result might be confusing.

Use of uninitialized value $x in say at perl_warning_1.pl line 7.
OK
42

Here, 'OK', the result of the print is seen after the warning, even though it was called before the code that generated the warning.

This strangeness is the result of IO buffering . By default Perl buffers STDOUT, the standard output channel, while it does not buffer STDERR, the standard error channel.

So while the word 'OK' is waiting for the buffer to be flushed, the warning message already arrives to the screen.

Turning off buffering

In order to avoid this you can turn off the buffering of STDOUT.

This is done by the following code: $| = 1; at the beginning of the script.

  1. use warnings ;
  2. use strict ;
  3. use 5.010 ;
  4. $ | = 1 ;
  5. print 'OK' ;
  6. my $x ;
  7. say $x ;
  8. $x = 42 ;
  9. say $x ;
OKUse of uninitialized value $x in say at perl_warning_1.pl line 7.
42

(The warning is on the same line as the OK because we have not printed a newline \n after the OK.)

The unwanted scope
  1. use warnings ;
  2. use strict ;
  3. use 5.010 ;
  4. my $x ;
  5. my $y = 1 ;
  6. if ( $y ) {
  7. my $x = 42 ;
  8. }
  9. say $x ;

This code too produces Use of uninitialized value $x in say at perl_warning_1.pl line 11.

I have managed to make this mistake several times. Not paying attention I used my $x inside the if block, which meant I have created another $x variable, assigned 42 to it just to let it go out of the scope at the end of the block. (The $y = 1 is just a placeholder for some real code and some real condition. It is there only to make this example a bit more realistic.)

There are of course cases when I need to declare a variable inside an if block, but not always. When I do that by mistake it is painful to find the bug.

[Sep 10, 2019] How do I avoid an uninitialized value

Sep 10, 2019 | stackoverflow.com

marto ,Jul 15, 2011 at 16:52

I use this scrub function to clean up output from other functions.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

my %h = (
    a => 1,
    b => 1
    );

print scrub($h{c});

sub scrub {
    my $a = shift;

    return ($a eq '' or $a eq '~' or not defined $a) ? -1 : $a;
}

The problem occurs when I also would like to handle the case, where the key in a hash doesn't exist, which is shown in the example with scrub($h{c}) .

What change should be make to scrub so it can handle this case?

Sandra Schlichting ,Jun 22, 2017 at 19:00

You're checking whether $a eq '' before checking whether it's defined, hence the warning "Use of uninitialized value in string eq". Simply change the order of things in the conditional:
return (!defined($a) or $a eq '' or $a eq '~') ? -1 : $a;

As soon as anything in the chain of 'or's matches, Perl will stop processing the conditional, thus avoiding the erroneous attempt to compare undef to a string.

Sandra Schlichting ,Jul 14, 2011 at 14:34

In scrub it is too late to check, if the hash has an entry for key key . scrub() only sees a scalar, which is undef , if the hash key does not exist. But a hash could have an entry with the value undef also, like this:
my %h = (
 a => 1,
 b => 1,
 c => undef
);

So I suggest to check for hash entries with the exists function.

[Sep 10, 2019] How do I check if a Perl scalar variable has been initialized - Stack Overflow

Sep 10, 2019 | stackoverflow.com

How do I check if a Perl scalar variable has been initialized? Ask Question Asked 8 years, 11 months ago Active 3 years ago Viewed 49k times 33 10


brian d foy ,Sep 18, 2010 at 13:53

Is the following the best way to check if a scalar variable is initialized in Perl, using defined ?
my $var;

if (cond) {
    $var = "string1";
}

# Is this the correct way?
if (defined $var) {
    ...
}

mob ,Sep 25, 2010 at 21:35

Perl doesn't offer a way to check whether or not a variable has been initialized.

However, scalar variables that haven't been explicitly initialized with some value happen to have the value of undef by default. You are right about defined being the right way to check whether or not a variable has a value of undef .

There's several other ways tho. If you want to assign to the variable if it's undef , which your example code seems to indicate, you could, for example, use perl's defined-or operator:

$var //= 'a default value';

vol7ron ,Sep 17, 2010 at 23:17

It depends on what you're trying to do. The proper C way to do things is to initialize variables when they are declared; however, Perl is not C , so one of the following may be what you want:
  1)   $var = "foo" unless defined $var;      # set default after the fact
  2)   $var = defined $var? $var : {...};     # ternary operation
  3)   {...} if !(defined $var);              # another way to write 1)
  4)   $var = $var || "foo";                  # set to $var unless it's falsy, in which case set to 'foo'
  5)   $var ||= "foo";                        # retain value of $var unless it's falsy, in which case set to 'foo' (same as previous line)
  6)   $var = $var // "foo";                  # set to $var unless it's undefined, in which case set to 'foo'
  7)   $var //= "foo";                        # 5.10+ ; retain value of $var unless it's undefined, in which case set to 'foo' (same as previous line)


C way of doing things ( not recommended ):

# initialize the variable to a default value during declaration
#   then test against that value when you want to see if it's been changed
my $var = "foo";
{...}
if ($var eq "foo"){
   ... # do something
} else {
   ... # do something else
}

Another long-winded way of doing this is to create a class and a flag when the variable's been changed, which is unnecessary.

Axeman ,Sep 17, 2010 at 20:39

If you don't care whether or not it's empty, it is. Otherwise you can check
if ( length( $str || '' )) {}

swilliams ,Sep 17, 2010 at 20:53

It depends on what you plan on doing with the variable whether or not it is defined; as of Perl 5.10, you can do this (from perl51000delta ):

A new operator // (defined-or) has been implemented. The following expression:

 $a // $b

is merely equivalent to

defined $a ? $a : $b

and the statement

$c //= $d;

can now be used instead of

$c = $d unless defined $c;

rafl ,Jun 24, 2012 at 7:53

'defined' will return true if a variable has a real value.

As an aside, in a hash, this can be true:

if(exists $h{$e} && !defined $h{$e})

[Sep 10, 2019] Perl Multidimensional Array

Sep 10, 2019 | www.javatpoint.com

The multi dimensional array is represented in the form of rows and columns, also called Matrix.

They can not hold arrays or hashes, they can only hold scalar values. They can contain references to another arrays or hashes.


Perl Multidimensional Array Matrix Example

Here, we are printing a 3 dimensional matrix by combining three different arrays arr1 , arr2 and arr3 . These three arrays are merged to make a matrix array final .

Two for loops are used with two control variables $i and $j .

  1. ## Declaring arrays
  2. my @arr1 = qw(0 10 0);
  3. my @arr2 = qw(0 0 20);
  4. my@arr3 = qw(30 0 0);
  5. ## Merging all the single dimensional arrays
  6. my @final = (\@arr1, \@arr2, \@arr3);
  7. print "Print Using Array Index\n" ;
  8. for (my $i = 0; $i <= $#final; $i ++){
  9. # $#final gives highest index from the array
  10. for (my $j = 0; $j <= $#final ; $j ++){
  11. print "$final[$i][$j] " ;
  12. }
  13. print "\n" ;
  14. }

Output:

Print Using Array Index
0 10 0
0 0 20 
30 0 0

Perl Multidimensional Array Initialization and Declaration Example

In this example we are initializing and declaring a three dimensional Perl array .

  1. @ array = (
  2. [1, 2, 3],
  3. [4, 5, 6],
  4. [7, 8, 9]
  5. );
  6. for ( $i = 0; $i < 3; $i ++) {
  7. for ( $j = 0; $j < 3; $j ++) {
  8. print "$array[$i][$j] " ;
  9. }
  10. print "\n" ;
  11. }

Output:

1 2 3
4 5 6 
7 8 9

[Sep 10, 2019] Perl Hashes - javatpoint

Sep 10, 2019 | www.javatpoint.com

The hashes is the most essential and influential part of the perl language. A hash is a group of key-value pairs. The keys are unique strings and values are scalar values.

Hashes are declared using my keyword. The variable name starts with a (%) sign.

Hashes are like arrays but there are two differences between them. First arrays are ordered but hashes are unordered. Second, hash elements are accessed using its value while array elements are accessed using its index value.

No repeating keys are allowed in hashes which makes the key values unique inside a hash. Every key has its single value.

Syntax:

  1. my %hashName = (
  2. "key" => "value" ;
  3. )

Perl Hash Accessing

To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.

  1. my %capitals = (
  2. "India" => "New Delhi" ,
  3. "South Korea" => "Seoul" ,
  4. "USA" => "Washington, D.C." ,
  5. "Australia" => "Canberra"
  6. );
  7. print "$capitals{'India'}\n" ;
  8. print "$capitals{'South Korea'}\n" ;
  9. print "$capitals{'USA'}\n" ;
  10. print "$capitals{'Australia'}\n" ;

Output:

New Delhi
Seoul
Washington, D.C.
Canberra

Perl Hash Indexing

Hashes are indexed using $key and $value variables. All the hash values will be printed using a while loop. As the while loop runs, values of each of these variables will be printed.

  1. my %capitals = (
  2. "India" => "New Delhi" ,
  3. "South Korea" => "Seoul" ,
  4. "USA" => "Washington, D.C." ,
  5. "Australia" => "Canberra"
  6. );
  7. # LOOP THROUGH IT
  8. while (( $key , $value ) = each(%capitals)){
  9. print $key . ", " . $value . "\n" ;
  10. }

Output:

Australia, Canberra
India, New Delhi
USA, Washington, D.C.
South Korea, Seoul

Perl sorting Hash by key

You can sort a hash using either its key element or value element. Perl provides a sort() function for this. In this example, we'll sort the hash by its key elements.

  1. my %capitals = (
  2. "India" => "New Delhi" ,
  3. "South Korea" => "Seoul" ,
  4. "USA" => "Washington, D.C." ,
  5. "Australia" => "Canberra"
  6. );
  7. # Foreach loop
  8. foreach $key (sort keys %capitals) {
  9. print "$key: $capitals{$key}\n" ;
  10. }

Output:

Australia: Canberra
India: New Delhi
South Korea: Seoul
USA: Washington: D.C.

Look at the output, all the key elements are sorted alphabetically.


Perl sorting Hash by its value

Here we'll sort hash by its value elements.

  1. my %capitals = (
  2. "India" => "New Delhi" ,
  3. "South Korea" => "Seoul" ,
  4. "USA" => "Washington, D.C." ,
  5. "UK" => "London"
  6. );
  7. # Foreach loop
  8. foreach $value (sort { $capitals { $a } cmp $capitals { $b } }
  9. keys %capitals)
  10. {
  11. print "$value $capitals{$value}\n" ;
  12. }

Output:

UK London
India New Delhi
South Korea Seoul
USA Washington D.C.

Look at the output, all the value elements are sorted alphabetically.

... ... ...


Perl Removing Hash Elements

To remove a hash element, use delete() function.

Here, we have removed both the key-value pairs which were added in the last example.

  1. my %capitals = (
  2. "India" => "New Delhi" ,
  3. "South Korea" => "Seoul" ,
  4. "USA" => "Washington, D.C." ,
  5. "Australia" => "Canberra"
  6. "Germany " => " Berlin"
  7. " UK " => "London"
  8. );
  9. while (( $key , $value ) = each(%apitals)){
  10. print $key . ", " . $value . "\n" ;
  11. }
  12. #removing element
  13. delete ( $capitals {Germany});
  14. delete ( $capitals {UK});
  15. # Printing new hash
  16. print "\n" ;
  17. while (( $key , $value ) = each(%capitals)){
  18. print $key . ", " . $value . "\n" ;
  19. }

Output:

Australia, Canberra
India, New Delhi
USA, Washington D.C.
South Korea, Seoul

Perl deleting Vs Undefining Hash Elements

deleting: In deleting, key-value pair will be deleted from the hash.

Syntax:

  1. delete ( $hash { $key });

undef: In undef, the value will be undefined but key will remain in the hash.

Syntax:

  1. undef $hash { $key };

[Sep 10, 2019] Pro Perl Debugging

May 12, 2012 | Slashdot

This title was published in hardcover in March 2005 by Apress, a relatively new member of the technical publishing world. The publisher has a Web page for the book that includes links to all of the source code in a Zip file, the table of contents in PDF format, and a form for submitting errata. The book comprises 269 pages, the majority of which are organized into 16 chapters:

Introduction (not to be confused with the true Introduction immediately preceding it),

Inspecting Variables and Getting Help, Controlling Program Execution, Debugging a Simple Command Line Program, Tracing Execution, Debugging Modules, Debugging Object-Oriented Perl, Using the Debugger As a Shell, Debugging a CGI Program, Perl Threads and Forked Processes, Debugging Regular Expressions, Debugger Customization, Optimization and Performance Hints and Tips, Command Line and GUI Debuggers, Comprehensive Command Reference, Book References and URLs.

hattmoward ( 695554 ) , Monday December 12, 2005 @02:11PM ( #14240507 )

Re:In defense of print statements ( Score: 5 , Insightful)

How many times is that conditional checked at runtime? They can add up. In perl, you could have it optimized away at compile time...

sub DEBUG() { return 1; }

...

DEBUG and print "value of blah:", $blah, $/;

but... TIMTOWTDI ;)
Mark_Uplanguage ( 444809 ) , Monday December 12, 2005 @03:13PM ( #14241006 )
Re:In defense of print statements ( Score: 4 , Informative)

When debugging I emphasize the use of "warn" over "print". It's the same syntax, but the warn statements don't get spooled and therefore their timing is quicker.

This is vital when you code just plain blows up. Using "print" means that a statement which got executed before the disaster may not make it to console, thus leading you to believe that it never got executed. "warn" avoids this problem and thus leads you to the problem more accurately. It also makes it easy to globally comment out the warn statements before going releasing the code.

codyk ( 857932 ) , Monday December 12, 2005 @03:20PM ( #14241071 )
Re:In defense of print statements ( Score: 1 )

Or you could just . . .

use Smart::Comments;
### Expected: "a bunch o stuff" Got: $stuff

. . . and have debugging statements that are easier to write, can be turned off in one place, and don't waste efficiency checking a bunch of conditionals.
see http://search.cpan.org/~dconway/Smart-Comments-1. 0 .1/lib/Smart/Comments.pm [cpan.org]

licamell ( 778753 ) * , Monday December 12, 2005 @01:47PM ( #14240302 )
use strict and Data::Dumper! ( Score: 5 , Insightful)

#! /usr/local/bin/perl
#
# Two things that make debugging perl easy:
#

use strict;
use Data::Dumper; ›

Baron von Leezard ( 675918 ) , Monday December 12, 2005 @03:22PM ( #14241092 )
Re:use strict and Data::Dumper! ( Score: 1 )

[That's one freelance Perl programmer I'll have to remember never to hire.]

Seriously, I'm one of those people who use a debugger every day. Actually, when I write new code in Perl, often the first thing I do is step through it in the debugger to make sure it does what I think it should. Especially in Perl, it is very easy to accidentally do something that's a little off. With the "wait until something goes wrong before I investigate" attitude demonstrated here, you'll never know anything is amiss until some nasty bug crops up as a result. Using the debugger to sanity check my code means that I catch most bugs before they ever cause problems.

I'm sure I'm going to get some snide remarks about this approach, but really, I've been a serious Perl programmer for about eight years now, and often write moderately complex Perl programs that work perfectly the first time--run through the debugger or not. I can't say that about any other language, and it's something most people can't say about any language, let alone Perl ;)

[Sep 10, 2019] logging - Perl - Output the log files - Stack Overflow

Aug 27, 2015 | stackoverflow.com

Perl - Output the log files Ask Question Asked 4 years ago Active 4 years ago Viewed 3k times 1 2


Arunesh Singh ,Aug 27, 2015 at 8:53

I have created a perl that telnet to multiple switches. I would like to check if telnet functions properly by telneting the switch.

This is my code to telnet to the switches:

#!/usr/bin/perl
use warnings;
use Net::Cisco;

open( OUTPUT, ">log.txt" );
open( SWITCHIP, "ip.txt" ) or die "couldn't open ip.txt";

my $count = 0;

while (<SWITCHIP>) {
    chomp($_);
    my $switch = $_;
    my $tl     = 0;
    my $t      = Net::Telnet::Cisco->new(
        Host => $switch,
        Prompt =>
            '/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
        Timeout => 5,
        Errmode => 'return'
    ) or $tl = 1;

    my @output = ();
    if ( $tl != 1 ) {
        print "$switch Telnet success\n";
    }
    else {
        my $telnetstat = "Telnet Failed";
        print "$switch $telnetstat\n";
    }
    close(OUTPUT);
    $count++;
}

This is my output status after I was testing 7 switches:

10.xxx.3.17 Telnet success
10.xxx.10.12 Telnet success
10.xxx.136.10 Telnet success
10.xxx.136.12 Telnet success
10.xxx.188.188 Telnet Failed
10.xxx.136.13 Telnet success

I would like to convert the telnet result as log file.
How to separate successful and failed telnet results by using perl?

Danny Luk ,Aug 28, 2015 at 8:40

Please Try the following
#!/usr/bin/perl
use warnings;
use Net::Cisco;
################################### S
open( OUTPUTS, ">log_Success.txt" );
open( OUTPUTF, ">log_Fail.txt" );
################################### E
open( SWITCHIP, "ip.txt" ) or die "couldn't open ip.txt";

my $count = 0;

while (<SWITCHIP>) {
    chomp($_);
    my $switch = $_;
    my $tl     = 0;
    my $t      = Net::Telnet::Cisco->new(
        Host => $switch,
        Prompt =>
            '/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
        Timeout => 5,
        Errmode => 'return'
    ) or $tl = 1;

    my @output = ();
################################### S
    if ( $tl != 1 ) {
        print "$switch Telnet success\n"; # for printing it in screen
        print OUTPUTS "$switch Telnet success\n"; # it will print it in the log_Success.txt
    }
    else {
        my $telnetstat = "Telnet Failed";
        print "$switch $telnetstat\n"; # for printing it in screen
        print OUTPUTF "$switch $telnetstat\n"; # it will print it in the log_Fail.txt
    }
################################### E
    $count++;
}
################################### S
close(SWITCHIP);
close(OUTPUTS);
close(OUTPUTF);
################################### E

Danny Luk ,Aug 28, 2015 at 8:39

In print statement after print just write the filehandle name which is OUTPUT in your code:
print OUTPUT "$switch Telnet success\n";

and

print OUTPUT "$switch $telnetstat\n";

A side note: always use a lexical filehandle and three arguments with error handling to open a file. This line open(OUTPUT, ">log.txt"); you can write like this:

open my $fhout, ">", "log.txt" or die $!;

Sobrique ,Aug 28, 2015 at 8:39

Use Sys::Syslog to write log messages.

But since you're opening a log.txt file with the handle OUTPUT , just change your two print statements to have OUTPUT as the first argument and the string as the next (without a comma).

my $telnetstat;
if($tl != 1) {
  $telnetstat = "Telnet success";
} else {
  $telnetstat = "Telnet Failed";
}
print OUTPUT "$switch $telnetstat\n";

# Or the shorter ternary operator line for all the above:
print OUTPUT $swtich . (!$tl ? " Telnet success\n" : " Telnet failed\n");

You might consider moving close to an END block:

END {
  close(OUTPUT);
}

Not only because it's in your while loop.

[Sep 06, 2019] Did CIA Director William Casey really say, "We'll know our disinformation program is complete when everything the American public believes is false"?

Sep 06, 2019 | www.quora.com

Matt Egan , former US Intelligence Officer (1967-2006) Answered Sep 8, 2017 · Author has 4.8k answers and 2.3m answer views

It does appear he said something very much along those lines, though I doubt it meant what it appears to mean absent the context. He made the statement not long after he became the Director of Central Intelligence, during a discussion of the fact that, to his amazement, about 80 percent of the contents of typical CIA intelligence publications was based on information from open, unclassified sources, such as newspapers and magazines.

Apparently, and reasonably, he judged that about the same proportion of Soviet intelligence products was probably based on open sources, as well. That meant that CIA disinformation programs directed at the USSR wouldn't work unless what was being disseminated by US magazines and newspapers on the same subjects comported with what the CIA was trying to sell the Soviets.

Given that the CIA could not possibly control the access to open sources of all US publications, the subjects of CIA disinformation operations had to be limited to topics not being covered by US public media. To be sure, some items of disinformation planted by the CIA in foreign publications might subsequently be discovered and republished by US media. I'm guessing the CIA would not leap to correct those items.

But that is a far cry from concluding that the CIA would (or even could) arrange that "everything the American public believes is false."

[Sep 06, 2019] The fact that our "leaders" continue to put our brave young men and women in harm's way, as we also kill millions of "others", and the American people stand idly by, is a proof of Casey quote . "So and so is evil and he oppresses his people, so we need to remove him and bring democracy to such and such country!"

Notable quotes:
"... You've heard of the "Manchurian Candidate"? We are the "Manchurian Populace". They spout the aforementioned mantra, and we all turn into mindless followers ..."
"... Assume that CIA launched disinformation in a hostile country to impact them. Then international news agencies picked it up and it got published by media in the US. If the disinformation were harmless to the US, then our Federal Government would not comment and would let the disinformation stand. To repudiate it might have bad effects on national security. Would this be a case of the CIA lying to the American people? No. ..."
"... The CIA once had influence in a number of English language publications abroad, some of which stories were reprinted in the US media. This was known as "blowback", and unintended in most cases. ..."
"... The CIA fabricated a story that the Russians in Afghanistan made plastic bombs in the shape of toys, to blow up children. Casey repeated this story, knowing it to be disinformation, as fact to US journalists and politicians. ..."
"... He doesn't need to have said it. CIA has run many disinformation campaigns against American public. Operation Mockingbird ..."
Sep 06, 2019 | www.quora.com

Thommy Berlin

Not that it matters. No conservative I know retains the ability to think off script, let alone rise above his indoctrination, and neither the script or their indoctrination allows this to be real.

So as far as they're concerned, it simply isn't possible.

Neither was David Stockman's admission that the idea of 'trickle down' was to bankrupt the federal government so they could finally do away with social security, while making themselves filthy rich...

Or Reagan being a traitor for negotiating with the Iranians BEFORE he was elected....

Or Bush II stealing the 2000 election....

Well...it's a LONG list....

Rael Sackey Answered Mar 16, 2019

The fact that our "leaders" continue to put our brave young men and women in harm's way, as we also kill millions of "others", and the American people stand idly by, is proof enough for me. "So and so is evil and he oppresses his people, so we need to remove him and bring democracy to such and such country!" This has been the game plan for decades. In the info age we know all this.

A convicted war criminal like Eliot Abrams is hired by a president the media and the Democrats hate and call a liar, and we suddenly suspend our disbelief, and follow blindly into another regime change war while we are buddies with many dictators around the world.

You've heard of the "Manchurian Candidate"? We are the "Manchurian Populace". They spout the aforementioned mantra, and we all turn into mindless followers of these MONSTERS! 806 views · View 3 Upvoters

Don Harmon, former intell analyst, former coll. poli sci professor. (1999-2013) Answered Jan 21, 2017 ·

About two years ago, one Barbara Honneger said in Quora that she was there. But I can find no credible news source that affirms this.

It is possible that Director Casey said it without any negative significance for the American people. How?

Assume that CIA launched disinformation in a hostile country to impact them. Then international news agencies picked it up and it got published by media in the US. If the disinformation were harmless to the US, then our Federal Government would not comment and would let the disinformation stand. To repudiate it might have bad effects on national security. Would this be a case of the CIA lying to the American people? No.

Fred Landis, Investigative Reporter Answered Sep 10, 2013 ·

The CIA once had influence in a number of English language publications abroad, some of which stories were reprinted in the US media. This was known as "blowback", and unintended in most cases.

The CIA fabricated a story that the Russians in Afghanistan made plastic bombs in the shape of toys, to blow up children. Casey repeated this story, knowing it to be disinformation, as fact to US journalists and politicians.

Ozgur Zeren , Author at ViaPopuli.com Answered Oct 22, 2014

He doesn't need to have said it. CIA has run many disinformation campaigns against American public. Operation Mockingbird

[Sep 02, 2019] perlcperl - a perl5 with classes, types, compilable, company friendly

Sep 02, 2019 | perl11.org

Compile-time optimizations

cperl adds many more traditional compile-time optimizations: more and earlier constant folding, type promotions, shaped arrays, usage of literal and typed constants, loop unrolling, omit unnecessary array bounds checks, function inlining and conversion of static method calls to functions.

Perl 5 only inlines constant function bodies with an explicit empty () prototype.

    sub x() {1+2} # inlined in perl5
    sub x   {1+2} # inlined in cperl only

cperl inlines constant function bodies even without empty prototype declaration, has type declarations for most internal ops, and optimizes these ops depending on the argument types; currently for all arithmetic unops and binops, and the data-accessing ops padsv, svop, and sassign. opnames.h stores PL_op_type_variants , all possible type promotions for each op. opcode.h stores PL_op_type with the type declarations of all ops.

[Sep 02, 2019] This Perl Goes To 11

Sep 02, 2019 | perl11.org

Perl 11 is not (yet) an actual version of Perl; rather, Perl 11 is currently a philosophy with 3 primary tenets:

Perl 11 promotes ideas which will make Perl 5 pluggable at the following levels:

This will open up the doors to many kinds of language / technology experimentation, without endangering the existing Perl 5 / CPAN code bases that we depend on every day.

Pluggable VMs would be parrot, p2, JVM or .NET running Perl5 and Perl 6 code. 5 + 6 == 11!

Perl 11 Projects

The following projects are important in reaching the vision of Perl 11:

RPerl

A Restricted Perl by Will Braswell which translates a medium-magic subset of Perl 5 into C/C++ using Inline::C and Inline::CPP

cperl

cperl is an improved variant of perl5, running all of perl5 and CPAN code. With many perl6 features, just faster.
Faster than perl5 and perl6. It is stable and usable, but still in development with many more features being added soon.

... ... ...

Perl 11 Links

[Sep 02, 2019] How to get the current line number of a file open using Perl

Sep 02, 2019 | stackoverflow.com

How to get the current line number of a file open using Perl? Ask Question Asked 8 years, 3 months ago Active 6 months ago Viewed 33k times 25 1


tadmc ,May 8, 2011 at 17:08

open my $fp, '<', $file or die $!;

while (<$fp>) {
    my $line = $_;
    if ($line =~ /$regex/) {
        # How do I find out which line number this match happened at?
    }
}

close $fp;

tchrist ,Apr 22, 2015 at 21:16

Use $. (see perldoc perlvar ).

tchrist ,May 7, 2011 at 16:48

You can also do it through OO interface:
use IO::Handle;
# later on ...
my $n = $fp->input_line_number();

This is in perldoc perlvar , too.

> ,

Don't use $. , nor $_ or any global variable. Use this instead:
while(my $line = <FILE>) {
  print $line unless ${\*FILE}->input_line_number == 1;
}

To avoid this and a lot of others Perl gotchas you can use on Atom or VSCode packages like linter-perl . Stop making Perl a write-only language !

[Aug 28, 2019] LogProgramInfo A Perl module to collect and log data for bioinformatics pipelines

Aug 28, 2019 | nlm.nih.gov
Find articles by John M. Macdonald Paul C. Boutros

Informatics and Biocomputing Program, Ontario Institute for Cancer Research, Suite 510, MaRS Centre, 661 University Ave, Toronto, Ontario Canada

Departments of Medical Biophysics and Pharmacology & Toxicology, University of Toronto, Toronto, Ontario Canada

Find articles by Paul C. Boutros Author information Article notes Copyright and License information Disclaimer Informatics and Biocomputing Program, Ontario Institute for Cancer Research, Suite 510, MaRS Centre, 661 University Ave, Toronto, Ontario Canada Departments of Medical Biophysics and Pharmacology & Toxicology, University of Toronto, Toronto, Ontario Canada John M. Macdonald, Email: ac.no.rcio@dlanodcam.nhoj . Contributor Information . corresponding author Corresponding author. # Contributed equally. Received 2015 Nov 26; Accepted 2016 Jun 1. Copyright © The Author(s) 2016

Open Access This article is distributed under the terms of the Creative Commons Attribution 4.0 International License ( http://creativecommons.org/licenses/by/4.0/ ), which permits unrestricted use, distribution, and reproduction in any medium, provided you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons license, and indicate if changes were made. The Creative Commons Public Domain Dedication waiver ( http://creativecommons.org/publicdomain/zero/1.0/ ) applies to the data made available in this article, unless otherwise stated. Go to:

Abstract Background

To reproduce and report a bioinformatics analysis, it is important to be able to determine the environment in which a program was run. It can also be valuable when trying to debug why different executions are giving unexpectedly different results.

Results

Log::ProgramInfo is a Perl module that writes a log file at the termination of execution of the enclosing program, to document useful execution characteristics. This log file can be used to re-create the environment in order to reproduce an earlier execution. It can also be used to compare the environments of two executions to determine whether there were any differences that might affect (or explain) their operation.

Availability

The source is available on CPAN (Macdonald and Boutros, Log-ProgramInfo. http://search.cpan.org/~boutroslb/Log-ProgramInfo/ ).

Conclusion

Using Log::ProgramInfo in programs creating result data for publishable research, and including the Log::ProgramInfo output log as part of the publication of that research is a valuable method to assist others to duplicate the programming environment as a precursor to validating and/or extending that research. Keywords: Reproducibility, Log, Environment Go to: Background

Reproducibility is a major concern in science as a whole, and computational biology in particular. For reproducibility, it is not sufficient to provide access to the raw data -- it is ever more critical to also provide access to the program code used to analyse those data [ 2 ]. But the program code is a dynamic mixture of program text, command line arguments, libraries, and various other environmental aspects -- all of which may need to be exactly reproduced to achieve the same results. So, simply providing access to the code used is not a complete solution. It is necessary, but not sufficient.

The need for reproducibility is growing because our pipelines are getting increasingly complex: a typical sequencing pipeline might involve a chain of a dozen unique tools [ 3 ]. But reproducing these pipelines is fundamentally very difficult, in part because it requires duplicating the versions of all dependent tools and libraries used in an analysis. Given the rapid rate of release of updates to common tools (e.g. BWA had 7 updates during the course of 2014 [ 4 ], this can be a significant challenge.

Among the best practices for scientific computing (e.g. [ 5 ]) is listed the need to collect and publish:

A large fraction of pipelines for bioinformatics are written in the Perl programming language (e.g. BioPerl [ 6 ]). However, for logging the precise state of a program at run-time, and capturing all the dependency versions and other key information, there are no automated choices available.

To resolve this issue, we introduce here the module Log::ProgramInfo to facilitate run-time logging of Perl-based pipelines, thereby directly improving the reproducibility of modern bioinformatic analyses.

A further advantage to such tracking information is the ability to test an analsis using later versions of the component tools to determine whether they provide different results (possibly more accurate if the later releases provide better resolution; possibly identifying erroneous results in the original analysis if the tools have been updated with critical fixes to their operation). Go to:

Related work

A search found some programs for related processes but nothing that served the same purposes.

There are some programs available to collect and document the computing process - by recording the steps invoved, including command lines and arguments during the actual data processing. Such a program could work well together with the described module but addresses a different aspect of the reproducibility issue. In our lab, when the workflow of the data analysis was sufficiently complex to require such a description, we instead write a program to encapsulate that process, so there is no long list of manual processing steps to document.

In particular, the program (ReproZip) [ 7 ] was capable of discovering and bundling together all of the programs used during the execution of a process. That seems to have different trade-offs. Such a bundle is only useful on similar hardware and it provides no possibility for assisting with script library version info, or in allowing a later run to use selected variations on the programming environment (such as allowing updated versions of programs that still have the same function but have had security problems fixed). Go to: Implementation

The Log::ProgramInfo module Macdonald and Boutros, Log-ProgramInfo. http://search.cpan.org/~boutroslb/Log-ProgramInfo/ is available as open source, and has been distributed on CPAN (the Comprehansive Perl Archive Network - used as the standard distribution mechanism for the vast majority of open source Perl modules, and described in the Perl documentation with the command "perldoc perlmodinstall").

Log::ProgramInfo is enabled simply by being included with a Perl use statement. Since its effect is global to the program, it should be enabled directly from the main program, or from a utility module that contains global configuration settings for a suite of programs.

Any desired setting of non-default values for the options can be provided either through environment variables, or as "import" list options.

When the module is used for the first time, the loading process carries out a number of actions for its operation:

Every time the Log::ProgramInfo module is used, the import list is processed and any values in it are used to update the option values. (The first time it is used, this processing happens after the initialization steps described above.)

That permits a common group of option settings be processed first, and then specific exceptions to that list over-ridden.

Any option settings provided in environent variables will over-ride the corresponding setting (whether a default or specified by the program import lists). This allows changing the option settings for individual runs so that the log can be suppressed, enabled, or redirected for a single run of the program.

The code that prints the log information ensures that it only executes once (in case multiple signals, or a signal during program termination, would cause it to be called additional times).

If the main body of the program changes a signal handler after Log::ProgramInfo has set it up, that will usually not interfere with Log::ProgramInfo. Usually, the program will catch signals and handle them in a way that allows it continue to operate, or to terminate with an exception. It is only if the program resets a signal handler to its default (abort without normal termination processing) that Log::ProgramInfo's log will not be written. That is not a problem for publication - if the program is being killed by some signal then it is not yet running successfully, and thus not yet ready for publication. However, it does mean that the log might not be available as a diagnostic aid in such situations.

For most cases, that is the only interaction between the program and Log::ProgramInfo.

The one additional interaction that might occur is if there is information unique to the program that is desired to be logged. The function

Log::ProgramInfo::add_extra_logger can be called by the program to specify a callable function that will write additional information to the log. (See the program documentation for precise details.) Go to: Results and discussion

Parameters are available to control the logging process: whether (and if so, where) a log is to be written. Choosing the location where the log is written allows collecting and managing this important information in a way that co-ordinates with the entire set of computational activity carried out for a research project (or an entire organisation's collection of research projects). The default name used for the log file includes the name of the program that is being reported upon as well as a time-stamp to distinguish separate runs -- you might choose to override the name or directory path to provide more complete organisation of logged results. Suppressing log output can be useful for runs that are not intended to generate reproducible results, such as while the software is being developed. However, even in such cases, it might turn out to be useful to have this log output to assist diagnosing problems with system configuration changes -- to confirm that the environment being used is the one that was intended and that updates have actually occurred, etc.

There is an additional parameter that permits the logged information to be sent to a separate logging mechanism, such as a Log4Perl log. This would allow the information to be collected with the other logged information from the program. The output to such logs is mixed with the other logged output from the program, and is also usually reformatted to some extent. Such logs cannot be processed by the Log::ProgramInfo parser provided with the package; hence the normal action for Log::ProgramInfo is to still write its own log file as well. Go to: Log output

The output created by Log::ProgramInfo contains the following information:

The format of the log file is designed to be easily parsed. A parsing subroutine is provided in the package. You could call that subroutine from a program that analyses logs according to your needs. See the program documentation for details. If you have written the log info using a logging module such as Log4Perl, you will have to separately extract the bare ProgramInfo log information out of that log, separating it from any other logging by the program, and removing any line decorations added by the log module. Go to: Example

Here is an example of using Log::ProgramInfo. Assume a simple program, called simple.pl.

An external file that holds a picture, illustration, etc. Object name is 13029_2016_55_Figa_HTML.gif Open in a separate window

When you run it, you get two lines of output.

An external file that holds a picture, illustration, etc. Object name is 13029_2016_55_Figb_HTML.gif Open in a separate window

The first line is the expected output from the program, the second line comes from Log::ProgramInfo to tell you that a log file was created, and where.

Now, take a look at the log file:

An external file that holds a picture, illustration, etc. Object name is 13029_2016_55_Figc_HTML.gif Open in a separate window

Now that you have a log file, you still have to make use of it. Typically, you would treat this log file as one of the output files of your processing activities. So, if you normally discard the output files (e.g. for a test run while developing the pipeline), you will likely also discard the log. On the other hand, for significant runs, you would collect the log file along with the other output files, labelling and storing them as appropriate for reference. The log file would be available as a synopsis of how the output data was created, ready to be used for publication, or reproducing the process (either to validate the results, or to apply the same process to additional data for subsequent research). Go to: Limitations

The C environment is not well built for program introspection activities such as determining which static and/or dynamic libraries have been linked into the program's executable image. This module lists the version of libc that was build into the perl binary - but that information can be out of date. A future release may try to get info about other libraries beyond libc.

Another major problem is that even if a perl module is downloaded from CPAN (which would be one way of ensuring that other people could get the same version), the install process that puts it into the library path for perl programs can be done in may ways, and often is not even done on the same computer as the one that is running the perl program. So, it is not easy to do any sort of detailed validation - the downloaded package bundle is not accessible in any determinable way (and possibly not at all) to the program itself (and thus to Log::ProgramInfo). While it would be possible to compute checksums for every library module that has been loaded, that would take a significant amount of time and is not currently being done. It may be added as an option that could request it explicitly. Go to: Conclusion

Module Log::ProgramInfo provides a convenient way of logging information about the way a program is run. Adding it to existing programs is as easy as adding one line to the program or any module the program already includes.

Log::ProgramInfo's output file can be easily included in the published results along with the actual source code (or references to where it can be found). With this log output, other researchers have information necessary to any meaningful attempt to reproduce the original research, either in the process of validating or extending that research.

Log::ProgramInfo is a good candidate for inclusion in modules intended to mandate standards, and may find use well beyond the field of bioinformatics. Go to: Availability and requirements

Go to: Acknowledgements

Special thanks to Julie Livingstone and Renasha Small-O'Connor for editorial assistance. Go to: Footnotes

cc Bug Reports To: BoutrosLabSoftware@oicr.on.ca

Funding

This study was conducted with the support of the Ontario Institute for Cancer Research to PCB through funding provided by the Government of Ontario. This work was supported by Prostate Cancer Canada and is proudly funded by the Movember Foundation – Grant #RS2014-01. Dr. Boutros was supported by a Terry Fox Research Institute New Investigator Award and a CIHR New Investigator Award. This project was supported by Genome Canada through a Large-Scale Applied Project contract to PCB, Dr. Sohrab Shah and Dr. Ryan Morin.

Authors' contributions

The module was written by the authors. Both authors read and approved the final manuscript.

Competing interests

The authors declare that they have no competing interests.

Go to: Contributor Information

John M. Macdonald, Email: ac.no.rcio@dlanodcam.nhoj .

Paul C. Boutros, Email: ac.no.rcio@sortuob.luap . Go to: References 1. Macdonald J, Boutros P. Log-ProgramInfo. module available from CPAN. http://search.cpan.org/~boutroslb/Log-ProgramInfo/ . 2. Nature-editorial. Code share. Nature. 2014;514. doi:10.1038/514536a. 3. Ewing A, Houlahan K, Hu Y, Ellrott K, Caloian C, Yamaguchi T, Bare J, P'ng C, Waggott D, Sabelnykova V, ICGC-TCGA DREAM Somatic Mutation Calling Challenge participants. Kellen M, Norman T, Haussler D, Friend S, Stolovitzky G, Margolin A, Stuart J, Boutros P. Combining accurate tumour genome simulation with crowd-sourcing to benchmark somatic single nucleotide variant detection. Nat Methods. 2015; 514 :623–30. doi: 10.1038/nmeth.3407. [ PMC free article ] [ PubMed ] [ CrossRef ] [ Google Scholar ] 4. sourceforge-BWA-files. Sourceforge File Listing for BWA on 30 Apr 2015. hand counted from web page. http://sourceforge.net/projects/bio-bwa/files/ . 5. Wilson G, Aruliah DA, Brown CT, Hong NPC, Davis M, Guy RT, Haddock SHD, Huff KD, Mitchell IM, Plumbley MD, Waugh B, White EP, Wilson P. Best practices for scientific computing. PLoS Biol. 2014;12(1). doi:10.1371/journal.pbio.1001745. [ PMC free article ] [ PubMed ] 6. Stajich J, Block D, Boulez K, Brenner SE, Dagdigian C, Fuellen G, Gilbert JGR, Korf I, Lapp H, Lehväslaiho H, Matsalla C, Mungall CJ, Osborne BI, Popock MR, Schattner P, Senger M, Stein L, Stupka E, Wilkinson MD, Birney E. The bioperl toolkit: Perl modules for the life sciences. Genome Res. 2002; 12 (10):1611–8. doi: 10.1101/gr.361602. [ PMC free article ] [ PubMed ] [ CrossRef ] [ Google Scholar ] 7. Chirigati F, Shasha D, Freire J. Presented as Part of the 5th USENIX Workshop on the Theory and Practice of Provenance. Berkeley: USENIX; 2013. Reprozip: Using provenance to support computational reproducibility. [ Google Scholar ]


Articles from Source Code for Biology and Medicine are provided here courtesy of BioMed Central

[Aug 28, 2019] Echo Command in Linux with Examples

Notable quotes:
"... The -e parameter is used for the interpretation of backslashes ..."
"... The -n option is used for omitting trailing newline. ..."
Aug 28, 2019 | linoxide.com

The -e parameter is used for the interpretation of backslashes

... ... ...

To create a new line after each word in a string use the -e operator with the \n option as shown
$ echo -e "Linux \nis \nan \nopensource \noperating \nsystem"

... ... ...

Omit echoing trailing newline

The -n option is used for omitting trailing newline. This is shown in the example below

$ echo -n "Linux is an opensource operating system"

Sample Output

Linux is an opensource operating systemjames@buster:/$

[Aug 27, 2019] How do I get the filename and line number in Perl - Stack Overflow

Aug 27, 2019 | stackoverflow.com

How do I get the filename and line number in Perl? Ask Question Asked 8 years, 10 months ago Active 8 years, 9 months ago Viewed 6k times 6


Elijah ,Nov 1, 2010 at 17:35

I would like to get the current filename and line number within a Perl script. How do I do this?

For example, in a file call test.pl :

my $foo = 'bar';
print 'Hello World';
print functionForFilename() . ':' . functionForLineNo();

It would output:

Hello World
test.pl:3

tchrist ,Nov 2, 2010 at 19:13

These are available with the __LINE__ and __FILE__ tokens, as documented in perldoc perldata under "Special Literals":

The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens; they will not be interpolated into strings. If there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value.

Eric Strom ,Nov 1, 2010 at 17:41

The caller function will do what you are looking for:
sub print_info {
   my ($package, $filename, $line) = caller;
   ...
}

print_info(); # prints info about this line

This will get the information from where the sub is called, which is probably what you are looking for. The __FILE__ and __LINE__ directives only apply to where they are written, so you can not encapsulate their effect in a subroutine. (unless you wanted a sub that only prints info about where it is defined)

,

You can use:
print __FILE__. " " . __LINE__;

[Aug 26, 2019] Static and state variables in Perl

Aug 26, 2019 | perlmaven.com

In most of the cases we either want a variable to be accessible only from inside a small scope, inside a function or even inside a loop. These variables get created when we enter the function (or the scope created by a a block) and destroyed when we leave the scope.

In some cases, especially when we don't want to pay attention to our code, we want variables to be global, to be accessible from anywhere in our script and be destroyed only when the script ends. In General having such global variables is not a good practice.

In some cases we want a variable to stay alive between function calls, but still to be private to that function. We want it to retain its value between calls.

Are you serious about Perl? Check out my Beginner Perl Maven book .
I have written it for you!

In the C programming language one can designate a variable to be a static variable . This means it gets initialized only once and it sticks around retaining its old value between function calls.

In Perl, the same can be achieved using the state variable which is available starting from version 5.10, but there is a construct that will work in every version of Perl 5. In a way it is even more powerful.

Let's create a counter as an example:

state variable
  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. sub count {
  5. state $counter = 0 ;
  6. $counter ++;
  7. return $counter ;
  8. }
  9. say count ();
  10. say count ();
  11. say count ();
  12. #say $counter;

In this example, instead of using my to declare the internal variable , we used the state keyword.

$counter is initialized to 0 only once, the first time we call counter() . In subsequent calls, the line state $counter = 0; does not get executed and $counter has the same value as it had when we left the function the last time.

Thus the output will be:

1
2
3

If we removed the # from last line, it would generate a Global symbol "$counter" requires explicit package name at ... line ... error when trying to compile the script. This just shows that the variable $counter is not accessible outside the function.

state is executed in the first call

Check out this strange example:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. sub count {
  5. state $counter = say "world" ;
  6. $counter ++;
  7. return $counter ;
  8. }
  9. say "hello" ;
  10. say count ();
  11. say count ();
  12. say count ();

This will print out

hello
world
2
3
4

showing that the state $counter = say "world"; line only gets executed once. In the first call to count() say , which was also added in version 5.10 , will return 1 upon success.

static variables in the "traditional" way
  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. {
  5. my $counter = 0 ;
  6. sub count {
  7. $counter ++;
  8. return $counter ;
  9. }
  10. }
  11. say count ();
  12. say count ();
  13. say count ();

This provides the same result as the above version using state , except that this could work in older versions of perl as well. (Especially if I did not want to use the say keyword, that was also introduced in 5.10.)

This version works because functions declarations are global in perl - so count() is accessible in the main body of the script even though it was declared inside a block. On the other hand the variable $counter is not accessible from the outside world because it was declared inside the block. Lastly, but probably most importantly, it does not get destroyed when we leave the count() function (or when the execution is outside the block), because the existing count() function still references it.

Thus $count is effectively a static variable.

First assignment time
  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. say "hi" ;
  5. {
  6. my $counter = say "world" ;
  7. sub count {
  8. $counter ++;
  9. return $counter ;
  10. }
  11. }
  12. say "hello" ;
  13. say count ();
  14. say count ();
  15. say count ();
hi
world
hello
2
3
4

This shows that in this case too, the declaration and the initial assignment my $counter = say "world"; happens only once, but we can also see that the assignment happens before the first call to count() as if the my $counter = say "world"; statement was part of the control flow of the code outside of the block.

Shared static variable

This "traditional" or "home made" static variable has an extra feature. Because it does not belong to the the count() subroutine, but to the block surrounding it, we can declare more than one functions in that block and we can share this static variable between two or even more functions.

For example we could add a reset_counter() function:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. {
  5. my $counter = 0 ;
  6. sub count {
  7. $counter ++;
  8. return $counter ;
  9. }
  10. sub reset_counter {
  11. $counter = 0 ;
  12. }
  13. }
  14. say count ();
  15. say count ();
  16. say count ();
  17. reset_counter ();
  18. say count ();
  19. say count ();
1
2
3
1
2

Now both functions can access the $counter variable, but still nothing outside the enclosing block can access it.

Static arrays and hashes

As of now, you cannot use the state declaration in list context. This means you cannot write state @y = (1, 1); . This limitation could be overcome by some extra coding. For example in this implementation of the Fibonacci series, we checked if the array is empty and set the default values:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. sub fib {
  5. state @y ;
  6. @y = ( 1 , 1 ) if not @y ; # workaround initialization
  7. push @y , $y [ 0 ]+ $y [ 1 ];
  8. return shift @y ;
  9. }
  10. say fib ();
  11. say fib ();
  12. say fib ();
  13. say fib ();
  14. say fib ();

Alternatively we could use the "old-style" static variable with the enclosing block.

Here is the example generating the Fibonacci series:

  1. use strict ;
  2. use warnings ;
  3. use 5.010 ;
  4. {
  5. my @y = ( 1 , 1 );
  6. sub fib {
  7. push @y , $y [ 0 ]+ $y [ 1 ];
  8. return shift @y ;
  9. }
  10. }
  11. say fib ();
  12. say fib ();
  13. say fib ();
  14. say fib ();

[Aug 26, 2019] Beginning Perl Programming From Novice to Professional

Aug 26, 2019 | www.amazon.com

Debugger Commands The debugger has many built-in commands. The most common are as follows.

Command

Meaning

!! cmd

Runs the command (cmd) in a separate process (this is typically a shell command)

h

Interactive help

H -num

Prints last "num" commands (excludes single character commands)

l

Lists the next line of code to be executed

n

Steps through a statement (if subroutines are called, executes over the subroutine)

q

Quits the debugger

s

Steps through a statement (if subroutines are called, executes one subroutine statement at a time)

V

Displays all of the variables in package (defaults to main)

[Aug 26, 2019] debugging - How can I debug a Perl script - Stack Overflow

Jun 27, 2014 | stackoverflow.com

Matthew Lock ,Jun 27, 2014 at 1:01

To run your script under perl debugger you should use -d switch:
perl -d script.pl

But perl is flexible. It supply some hooks and you may force debugger to work as you want

So to use different debuggers you may do:

perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl

Look these modules here and here

There are several most interesting perl modules that hook into perl debugger internals: Devel::NYTProf , Devel::Cover

And many others

XXX,

If you want to do remote debug (for cgi or if you don't want to mess output with debug command line) use this:

given test:

use v5.14;
say 1;
say 2;
say 3;

Start a listener on whatever host and port on terminal 1 (here localhost:12345):

$ nc -v -l localhost -p 12345

for readline support use rlwrap (you can use on perl -d too):

$ rlwrap nc -v -l localhost -p 12345

And start the test on another terminal (say terminal 2):

$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test

Input/Output on terminal 1:

Connection from 127.0.0.1:42994

Loading DB routines from perl5db.pl version 1.49
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(test:2): say 1;
  DB<1> n
main::(test:3): say 2;
  DB<1> select $DB::OUT

  DB<2> n
2
main::(test:4): say 3;
  DB<2> n
3
Debugged program terminated.  Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.  
  DB<2>

Output on terminal 2:

1

Note the sentence if you want output on debug terminal

select $DB::OUT

If you are vim user, install this plugin: dbg.vim which provides basic support for perl

[Aug 26, 2019] D>ebugging - How to use the Perl debugger

Aug 26, 2019 | stackoverflow.com
This is like "please can you give me an example how to drive a car" .

I have explained the basic commands that you will use most often. Beyond this you must read the debugger's inline help and reread the perldebug documentation

The debugger will do a lot more than this, but these are the basic commands that you need to know. You should experiment with them and look at the contents of the help text to get more proficient with the Perl debugger

[Aug 03, 2019] Was future President George H. W. Bush at Dealey Plaza during JFK's assassination - Quora

Notable quotes:
"... There is a photo of someone who looks like him standing in front of the School Book Depository. Bush is one of the few people in America who can't remember where he was that day. ..."
Aug 03, 2019 | www.quora.com

Kevin Stewart , Writer Answered Nov 4 2018 · Author has 370 answers and 39.7k answer views

There is some flimsy photo evidence of someone who looked like him in Dealey Plaza, so my answer would be, "not sure." But anecdotally, there sure seems to be a large number of "coincidences" around a guy who could apparently walk across a snow covered field without leaving foot prints , so maybe.

Since the beginning, the rumored driving motive for JFK's assassination, (from both sides really) was the cluster-fuck known as "The Bay of Pigs invasion," so we'll start there. At the end of Mark Lane's book "Plausible Denial," (the account of E. Howard Hunt's ill-fated lawsuit against The Liberty Lobby) some interesting facts about the Bay of Pigs invasion were tossed out that leaves one scratching his or her head and wondering if 41 had anything to do with it. The operation was ostensibly to deliver small arms and ordnance to a (turns out to be fictional) 25,000 man rebel army that was in the Cuban hills waiting for help to depose Castro.

The US Navy supplied a couple of ships, but they were decommissioned, had their numbers scraped off, and were renamed the "Houston" and the "Barbara," (or the Spanish spelling of Barbara.) This is while 41 was living in Houston with his wife Barbara. Also, the CIA code name for the invasion was "Operation Zapata."

This while the name of 41's business was "Zapata Offshore." (Or something like that. 41 had business' using Zapata's name since his days as an oilman in Midland Texas.) The day after Kennedy's killing, a George Bush met with Army Intel. What went on in that meeting is a mystery, and the CIA unconvincingly claims that they had another guy working for them named George Bush, only he wasn't hired until 1964 and his expertise was meteorology so it's difficult to understand why they wanted to talk with him on that day. Then there's the fact that Oswald's CIA handler, a guy name Georges DeMorinshilt (sp?) had the name George (Poppy) Bush in his address book along with 41's Houston address and phone number.

Of course this is all coincidental, but consider: 41 was a failed two-term congressman who couldn't hold his seat, (in Houston Texas of all places) and yet was made by Nixon the ambassador to the UN, then Ford named him ambassador to China and the Director of the CIA. Wow! What a lucky guy.

So was he involved with the Kennedy assassination and photographed in Dealey Plaza? Don't know. I was 13 at the time, but in the intervening years, the politics in this country, especially relating to the Republican Party, have become shall we say, "Kalfkaesque."

Steven Hager , Author of "Killing Kennedy." Updated Dec 31, 2018 · Author has 1.2k answers and 1.4m answer views

There is a photo of someone who looks like him standing in front of the School Book Depository. Bush is one of the few people in America who can't remember where he was that day.

There is also a memo by J.Edgar Hoover referencing a "George Bush of the CIA" reporting on "misguided Cubans" in Dallas that day. The CIA had a safe house stuffed with Cuban agents in the Oak Cliff neighborhood, and Lee Harvey Oswald rented a room nearby shortly before the assassination took place.

Michael Tarnpoll , We came so goddamn close Answered Feb 2, 2017 · Author has 3.7k answers and 1.5m answer views

The George Bush connections to JFK's assassination

Astoundingly, Bush, the elder, claims that he does not remember where he was when Kennedy was assassinated. I do. I'll bet a dollar that you do (if old enough). Everyone above the age of fifty-five does except George H. W. Bush. He does however, remember that he was not at Dealey Plaza at the time.

It is interesting to note that photographs and videos exist showing a man who looks very much like Bush, at the site, at the time. It was not difficult to find them on line in the past. Now, they seem to have been expunged somehow, though a few blurry photos can still be found.

[Apr 27, 2019] What are the main differences between religion and ideology - Quora

Apr 27, 2019 | www.quora.com

a rQU d JV lm b cJr y s TObs M Mr a sqQCs n J a Ryv g Fb e G E aNWBB n k g wuli i Pu n LN e MI cLaG A GkdE D KPJJd S ZHmQO e ny l JACzT f gvhU S hoqBB e QsBBn r NqGDf v z i m c aXQ e zSU Fc P A u Txrqy s pVS Free Active Directory password expiration notification tool. Free tool to automatically remind users about password expiration via email, SMS, and push notifications. L wjx e Lpor a zsMV r WmU n nfoVQ eftBn M UtIUC o i r oi e Zej Y a sk t gkK TOD m mT a JbQx n rIFL a De g luOwd e GKdRL e x n xIIq g uKmA i I n IPuF e QvFM . xLEY c cMetZ o Gtv m qNSFZ You dismissed this ad. The feedback you provide will help us show you more relevant content in the future. Undo Answer Wiki 12 Answers Christopher Story

Christopher Story Lives in Hawai'i 25.3k answer views 788 this month Christopher Story Christopher Story Answered Sep 1 2015 · Author has 64 answers and 25.3k answer views One could say that an ideology is a religion if and only if it is theocratic, but I find Yuval Harari's understanding of religion less arbitrary and more compelling.

"Religion is any system of human norms and values that is founded on a belief in superhuman laws. Religion tells us that we must obey certain laws that were not invented by humans, and that humans cannot change at will. Some religions, such as Islam, Christianity and Hinduism, believe that these super-human laws were created by the gods. Other religions, such as Buddhism, Communism and Nazism, believe that these super-human laws are natural laws. Thus Buddhists believe in the natural laws of karma, Nazis argued that their ideology reflected the laws of natural selection, and Communists believe that they follow the natural laws of economics. No matter whether they believe in divine laws or in natural laws, all religions have exactly the same function: to give legitimacy to human norms and values, and to give stability to human institutions such as states and corporations. Without some kind of religion, it is simply impossible to maintain social order. During the modern era religions that believe in divine laws went into eclipse. But religions that believe in natural laws became ever more powerful. In the future, they are likely to become more powerful yet. Silicon Valley, for example, is today a hot-house of new techno-religions, that promise humankind paradise here on earth with the help of new technology."

[Apr 06, 2019] Would you fly Boeing 737 Max 8 ever again - Quora

Notable quotes:
"... No. Possibly Boeing & the FAA will solve the immediate issue, but they have destroyed Trust. ..."
"... It has emerged on the 737MAX that larger LEAP-1B engines were unsuited to the airframe and there is no way now to alter the airframe to balance the aircraft. ..."
"... Boeing failed to provide training or training material to pilots or even advise them the existence of MCAS. There was a complex two step process required of pilots in ET302 and JT610 crashes and their QRH handbook did not explain this: ..."
Apr 06, 2019 | www.quora.com

Would you fly Boeing 737 Max 8 ever again? Update Cancel

Simon Gunson , PPL aviation enthusiast Answered Mar 25, 2019 · Author has 141 answers and 981.7k answer views

No. Possibly Boeing & the FAA will solve the immediate issue, but they have destroyed Trust.

Other brands of aircraft like Airbus with AF447 established trust after their A330 aircraft plunged into the Atlantic in a mysterious accident.

With Airbus everyone saw transparency & integrity in how their accidents were investigated. How Boeing & FAA approached accident investigation destroyed public Trust.

By direct contrast in the mysterious disappearance of MH370, Boeing contributed nothing to the search effort and tried to blame the pilot or hijackers.

With the 737MAX in Lion Air and Ethiopian crashes Boeing again tried to blame pilots, poor training, poor maintenance and then when mechanical defect was proven, Boeing tried to downplay how serious the issue was and gave false assurances after Lion Air that the plane was still safe. ET302 proved otherwise.

It is no longer possible to trust the aircraft's certification. It is no longer possible to trust that safety was the overriding principle in design of the Boeing 737 MAX nor several other Boeing designs for that matter.

The Public have yet to realize that the Boeing 777 is an all electric design where in certain scenarios like electrical fire in the avionics bay, an MEC override vent opens allowing cabin air pressure to push out smoke. This silences the cabin depressurization alarms.

As an electrical failure worsens, in that scenario another system called ELMS turns off electrical power to the Air Cycle Machine which pumps pressurized air into the cabin. The result of ELMS cutting power means the override vent fails to close again and no new pressurized air maintains pressure in the cabin. Pilots get no warning.

An incident in 2007 is cited as AD 2007–07–05 by the FAA in which part but not all of this scenario played out in a B777 at altitude.

MH370 may have been the incident in which the full scenario played out, but of course Boeing is not keen for MH370 to be found and unlike Airbus which funded the search for AF447, Boeing contributed nothing to finding MH370.

It has emerged on the 737MAX that larger LEAP-1B engines were unsuited to the airframe and there is no way now to alter the airframe to balance the aircraft.

It also emerged that the choice to fit engines to this airframe have origins in a commercial decision to please Southwest Airlines and cancel the Boeing 757.

Boeing failed to provide training or training material to pilots or even advise them the existence of MCAS. There was a complex two step process required of pilots in ET302 and JT610 crashes and their QRH handbook did not explain this:

Boeing pilots had less than 40 SECONDS to over-ride automated system

The MAX is an aerodynamically unbalanced aircraft vulnerable to any sort of disruption, ranging from electrical failure, out of phase generator, faulty AOA sensor, faulty PCU failure alert, digital encoding error in the DFDAU.

Jason Eaton Former Service Manager Studied at University of Life Lives in Sydney, Australia 564k answer views 50.7k this month Answered Mar 24, 2019 ·

No I wouldn't. I'm not a pilot or an aerospace technician but I am a mechanical engineer, so I know a little bit about physics and stuff.

The 737–8 is carrying engines it was never designed for, that cause it to become inherently unstable. So unstable in fact, that it can't be controlled by humans and instead relies on computer aided control to maintain the correct attitude, particularly during ascent and descent.

The MCAS system is, effectively, a band aid to fix a problem brought about by poor design philosophy. Boeing should have designed a new airframe that complements the new engines, instead of ruining a perfectly good aircraft by bolting on power units it's not designed to carry, and then trying to solve the resulting instability with software. And if that isn't bad enough, the system relies on data from just the one sensor which if it doesn't agree with, it'll force the aircraft nose down regardless of the pilots' better judgement.

That might be ok for the Eurofighter Typhoon but it's definitely not ok for fare paying passengers on a commercial jetliner.

So, no. I won't be flying on a 737–8 until it's been redesigned to fly safely. You know, like a properly designed aeroplane should. 4.8k Views · View 36 Upvoters

[Mar 25, 2019] What do you think of Jared Kushner getting ready to unveil his economic plan for peace in the Middle East

Notable quotes:
"... He and the rest of his family are all crooks as are most politicians. Deals are made between thieves. Wealth serves as a mask. ..."
Mar 25, 2019 | www.quora.com

What do you think of Jared Kushner getting ready to unveil his economic plan for peace in the Middle East?

https://thehill.com/news-by-subject/foreign-policy/429053-kushner-to-unveil-economic-plan-for-middle-east-peace-report

Christina Fabian , lives in San Francisco Answered Feb 8

He and the rest of his family are all crooks as are most politicians. Deals are made between thieves. Wealth serves as a mask.

I wonder how much he will make! Am so sick at the lack of morals among officials all over the world. Do good because it is the right thing to do not because of the accolades. Let thereby real judge!

[Mar 25, 2019] Is Jared Kushner, Trump's son-in-law, the man to bring peace to the Middle East- - Quora

Jan 21, 2017 | www.quora.com

John-Paul Wilson Answered Jan 21 2017

No! Of course not. Why does anyone believe this nonsense!

First off, I think by "bring peace to the Middle East" you must be referring to "solve the Israeli-Palestinian dilemma". There are numerous conflicts in the broader Middle East that make broader peace impossible.

Jared Kushner has no diplomatic experience. He doesn't seem to have any special knowledge about the conflict between Israel and the Palestinians. Being raised an Orthodox Jew, I think it will be impossible for the Palestinians to see him as a neutral party.

Here's something that people should have learned before the election: p... (more)

[Mar 20, 2019] How to I print to STDERR only if STDOUT is a different destination?

Mar 14, 2013 | stackoverflow.com

squiguy, Mar 14, 2013 at 19:06

I would like Perl to write to STDERR only if STDOUT is not the same. For example, if both STDOUT and STDERR would redirect output to the Terminal, then I don't want STDERR to be printed.

Consider the following example (outerr.pl):

#!/usr/bin/perl

use strict;
use warnings;

print STDOUT "Hello standard output!\n";
print STDERR "Hello standard error\n" if ($someMagicalFlag);
exit 0

Now consider this (this is what I would like to achieve):

bash $ outerr.pl
Hello standard output!

However, if I redirect out to a file, I'd like to get:

bash $ outerr.pl > /dev/null
Hello standard error

and similary the other way round:

bash $ outerr.pl 2> /dev/null
Hello standard output!

If I re-direct both out/err to the same file, then only stdout should be displayed:

bash $ outerr.pl > foo.txt 2>&1
bash $ cat foo.txt
Hello standard output!

So is there a way to evaluate / determine whether OUT and ERR and are pointing to the same "thing" (descriptor?)?

tchrist ,Mar 15, 2013 at 5:07

On Unix-style systems, you should be able to do:
my @stat_err = stat STDERR;
my @stat_out = stat STDOUT;

my $stderr_is_not_stdout = (($stat_err[0] != $stat_out[0]) ||
                            ($stat_err[1] != $stat_out[1]));

But that won't work on Windows, which doesn't have real inode numbers. It gives both false positives (thinks they're different when they aren't) and false negatives (thinks they're the same when they aren't).

Jim Stewart ,Mar 14, 2013 at 20:59

You can do that (almost) with -t:
-t STDERR

will be true if it is a terminal, and likewise for STDOUT.

This still would not tell you what terminal, and if you redirect to the same file, you may stilll get both.

Hence, if

-t STDERR && ! (-t STDOUT) || -t STDOUT && !(-t STDERR)

or shorter

-t STDOUT ^ -t STDERR  # thanks to @mob

you know you're okay.

EDIT: Solutions for the case that both STDERR and STDOUT are regular files:

Tom Christianson suggested to stat and compare the dev and ino fields. This will work in UNIX, but, as @cjm pointed out, not in Windows.

If you can guarantee that no other program will write to the file, you could do the following both in Windows and UNIX:

  1. check the position the file descriptors for STDOUT and STDERR are at, if they are not equal, you redirected one of them with >> to a nonempty file.
  2. Otherwise, write 42 bytes to file descriptor 2
  3. Seek to the end of file descriptor 1. If it is 42 more than before, chances are high that both are redirected to the same file. If it is unchanged, files are different. If it is changed, but not by 42, someone else is writing there, all bets are off (but then, you're not in Windows, so the stat method will work).

[Mar 06, 2019] Who will win the 2020 United States presidential election - Quora

Mar 06, 2019 | www.quora.com

Emmanuel Gautier

Emmanuel Gautier I know some stuff, still trying to figure out all the rest. MSc Industrial Engineering & Management, École Centrale Paris Graduated 2017 Lives in France 2.4m answer views 11.9k this month Top Writer 2018 fr Active in French 6 Answers Emmanuel Gautier , Assiduous foreign observer of US Politics Updated Jun 1, 2018 · Author has 350 answers and 2.4m answer views

As much as I hate to say this, I think that as things stand right now, it's going to be Trump.

I'm sorry, what? You mean the most unpopular President in modern US political history? Donald 'both sides' Trump? Donald 'muslim ban' Trump? Donald 'covfefe' Trump? Donald 'golf at Mar-a-Lago every weekend while the country's trying to keep it together' Trump?

Yup, that Trump.

Now, this is the part when you pull out some pen and paper, and start proving to me, using political theorems, why a President with such low approval ratings eight months into his first term is pretty much doomed for reelection.

And that's when I point out that we've been over this kind of math, a million times, remember? That was the entire 2016 election in a nutshell. If I had a dollar every time I heard 'Trump has no path to 270 Electoral votes', 'Trump is the most unpopular candidate in an election ever', 'Trump is spending less money on grassroots operations than Clinton' last year, I could've formed a Super PAC. Election Day should've made it pretty clear, by now, that the usual political math does not apply to Trump.

Still, a 39% approval rating ? That's extremely low so early into his term.

Is it? He's at 40% on polls of likely or registered voters. There are 200 million registered voters in the US. So Trump has a base of 80 million registered voters . He won with less than 63 million in 2016. I'd say that's more than enough.

Of course, I'm not saying all 80 million will turn up in 2020. I'm just saying that right now, he has more voters who think he's doing a good job than he needs to be elected, even after what he's done so far in his term .

But isn't that the point? He's going to do more crazy stuff and end up losing support?

That's not how things have turned out so far. Remember when Trump said he could go on 5th Ave, shoot someone, and not lose a point in the polls? He was absolutely right.

Most politicians work hard on their respectability. Not only does it cost them a lot when they show the slightest crack, it ends up looking more like superiority. Trump made the insane wager that turning the problem upside down could work, and it did. It cost him hatred from half the country, but it earned him unconditional support from the other half.

His vulgarity - note that the word comes from Latin, ' vulgus ', which means 'the people' - puts the bar so low that nothing he does or says does any real damage to him.

And more importantly, his demeanor screams, ' I am like you. I don't speak using fancy words. I'm not PC - when I think something, I just say it, even if it's kinda sexist or racist. At night I just sit and watch Fox News while tweeting mean stuff.'

Trump replaced the 'superego' politician - one that Americans could aspire to be - with the 'id' politician - one that Americans want to be . People don't want to be first of their class, or do their homework. They don't want to be war heroes or presidents of the Harvard Law Review - at best, they aspire to . What people want , is to make money, fuck models, and give orders, all with minimal effort. And that's the fantasy that Trump sells them.

Of course, that's not true of every American, but it's true of enough of them. And now that they've stuck with him through so much, there's little that could turn them around, as long as he maintains this course.

So I think that Trump won't come down much lower than 30–32%. He could go up again during the next election cycle and win.

No, wait. Some of his base doesn't like the character, they just have faith in his nationalist agenda because he says he's going to bring jobs back. They're going to stop supporting him when it doesn't work.

I'm not sure. He's proven quite masterful at bypassing the mainstream media, talking directly to the people, destroying the concept of truth, and painting whoever's in his way as 'the establishment' and 'the elites', all convenient opponents.

There are many ways he could spin his term as a win, or at least blame his failings on others. Hell, he's already campaigning for 2020. I mean, literally . He's started holding rallies for 2020 as soon as he got into office.

I'm pretty sure that right now, Trump supporters believe that the failure to repeal Obamacare was entirely on the GOP establishment. And see how he's already boasting that the job market is doing well, even though there's no policy he's responsible for that could possibly have caused this? To be fair, all Presidents tend to take undue credit for jobs they have little to do with, but still.

Trump hates his job. He's a child who wanted a toy because it was shiny and realized it wasn't meant for him. Maybe he won't run, or sabotage his campaign?

That's right, Trump hates the job. But he's never happier than when he's running, and winning. That's why he can't stop talking about his 2016 win. That's why he's already holding those rallies. He's deeply insecure, and his political career is just a way for him to fill this enormous affection deficit that he has. He is going to run in 2020, and he'll want to win.

At the end of the day, Trump only won because he ran against Hillary Clinton. She was the weakest candidate ever.

No she wasn't. She was ultra-qualified, and had the temperament. She just happened, in an election that was marked by populism, to epitomize the career politician. Bernie scathed her, for Trump to finish her in the General Election. Put down the forks and torches, Bernie bros, I'm not saying it was his fault. He ran a campaign against her, and ultimately conceded and endorsed her. He did what was right all the way through, but the fact is that she came out of the primary quite damaged.

Objectively, the emails were nothing compared to everything Trump had (Russian ties, Trump U, Trump foundation, allegations of sexual harrassment and assault), but remember what I said about setting the bar low?

That's probably what's going to happen with his opponent next time: the Democrats are going to look for an unsinkable candidate, and the harder they'll try, the more Trump will exploit the smallest flaw to maximum effect , while being immune to scandal himself. Once again, he's going to be the champion of right-wingers who want him to 'stick it to those arrogant Dems'.

Democrats cannot defeat Trump just by taking the moral high ground. It simply doesn't work, and Trump understands this perfectly. He sets traps for them, and they keep falling into them, as Bannon says: ' The Democrats, the longer they talk about identity politics, I got 'em. I want them to talk about racism every day. If the left is focused on race and identity, and we go with economic nationalism, we can crush the Democrats.' [1]

Every time he says something awful, he knows that his supporters are either going to agree or not care, and that Democrats and the media will enter the usual cycle of hysterical outrage that accomplishes nothing.

So the Dems haven't proved to me that they're capable of inspiring trust and desire from voters. All they have to propose so far is 'not Trump'. That makes me pessimistic about their 2020 campaign. And that's not even counting the possibility of a third-party run that could split the left and center vote.

Maybe the undoing of Trump will come from the GOP itself. They don't support his platform of economic nationalism.

As long as Trump does the tax cuts for corporations and the wealthy, shrinks the federal government and keeps the NRA happy, the GOP won't ditch him. There will be some clashes between Ryan/McConnell and Trump, but it won't be enough to make them renounce the White House just to get rid of him.

Some 'mavericks' such as McCain (who may have been one of the three GOP Senators who killed the Obamacare repeal, but still votes with Trump 83% of the time [2] ) may openly criticize him or even endorse his opponent, but it won't be enough, just like it wasn't enough during the Access Hollywood turmoil. He played it by saying 'the shackles are off now', and it worked just fine. His base doesn't care about the GOP, they care about him.

Okay. But hey, one more thing. Russia. What if Trump's impeached?

We're gonna have to wait for the results of the investigation for that. Even if they are incriminating, the only real juror here is the public. As long as his public support doesn't fall apart, the GOP-controlled house will not impeach, and the GOP-controlled Senate will not convict.

So, is there just no way of defeating Trump in 2020?

It's not inevitable. All I'm saying is, right now his re-election looks increasingly likely. If Democrats changed their approach, they could find a candidate suited for fighting Trump. If Trump himself changed course, he could finally alienate his base. But it seems that right now, we're stuck in a Nash equilibrium: there are no direct incentives for anyone to behave differently than they are.

Trump is a parasite , that dwells in everyone's cerebrum, living off of attention, obsession even. He constantly lays larvas in our minds, in the form of brash statements or actions. They feed off his supporters' delight and his opponents' outrage, growing into more Trump memes that remain engraved in our brains. We may move on from him one day, but it's going to take waking up from this state of hypnosis he put us in, and start looking around for actual alternatives.

Footnotes

[1] What Steve Bannon gets right about Democrats -- and wrong about Trump

[2] Tracking Congress In The Age Of Trump

[Feb 21, 2019] perl - How to prompt for input and exit if the user entered an empty string - Stack Overflow

Feb 20, 2019 | stackoverflow.com

NewLearner ,Mar 12, 2012 at 3:22

I'm new to Perl and I'm writing a program where I want to force the user to enter a word. If the user enters an empty string then the program should exit.

This is what I have so far:

print "Enter a word to look up: ";

chomp ($usrword = <STDIN>);

DVK , Nov 19, 2015 at 19:11

You're almost there.
print "Enter a word to look up: ";
my $userword = <STDIN>; # I moved chomp to a new line to make it more readable
chomp $userword; # Get rid of newline character at the end
exit 0 if ($userword eq ""); # If empty string, exit.

Pondy , Jul 6 '16 at 22:11

File output is buffered by default. Since the prompt is so short, it is still sitting in the output buffer. You can disable buffering on STDOUT by adding this line of code before printing...
select((select(STDOUT), $|=1)[0]);

[Jan 29, 2019] New Perl function each is available in Perl 5.14 and later

Jan 29, 2019 | perldoc.perl.org

called on a hash in list context, returns a 2-element list consisting of the key and value for the next element of a hash. In Perl 5.12 and later only, it will also return the index and value for the next element of an array so that you can iterate over it; older Perls consider this a syntax error. When called in scalar context, returns only the key (not the value) in a hash, or the index in an array.

Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash. Any insertion into the hash may change the order, as will any deletion, with the exception that the most recent key returned by each or keys may be deleted without changing the order. So long as a given hash is unmodified you may rely on keys , values and each to repeatedly return the same order as each other. See Algorithmic Complexity Attacks in perlsec for details on why hash order is randomized. Aside from the guarantees provided here the exact details of Perl's hash algorithm and the hash traversal order are subject to change in any release of Perl.

After each has returned all entries from the hash or array, the next call to each returns the empty list in list context and undef in scalar context; the next call following that one restarts iteration. Each hash or array has its own internal iterator, accessed by each , keys , and values . The iterator is implicitly reset when each has reached the end as just described; it can be explicitly reset by calling keys or values on the hash or array. If you add or delete a hash's elements while iterating over it, the effect on the iterator is unspecified; for example, entries may be skipped or duplicated--so don't do that. Exception: It is always safe to delete the item most recently returned by each , so the following code works properly:

  1. while ( my ( $key , $value ) = each %hash ) {
  2. print $key , "\n" ;
  3. delete $hash { $key } ; # This is safe
  4. }

Tied hashes may have a different ordering behaviour to perl's hash implementation.

This prints out your environment like the printenv(1) program, but in a different order:

  1. while ( my ( $key , $value ) = each %ENV ) {
  2. print "$key=$value\n" ;
  3. }

Starting with Perl 5.14, an experimental feature allowed each to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

As of Perl 5.18 you can use a bare each in a while loop, which will set $_ on every iteration.

  1. while ( each %ENV ) {
  2. print "$_=$ENV{$_}\n" ;
  3. }

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:

  1. use 5.012 ; # so keys/values/each work on arrays
  2. use 5.018 ; # so each assigns to $_ in a lone while test

See also keys , values , and sort .

[Jan 17, 2019] How do I launch the default web browser in Perl on any operating system

Jan 17, 2019 | stackoverflow.com

The second hit on "open url" at search.cpan brings up Browser::Open:

use Browser::Open qw( open_browser );

my $url = 'http://www.google.com/';
open_browser($url);

If your OS isn't supported, send a patch or a bug report.

--cjm

More at Stack Overflow More at Stack Overflow

[Jan 10, 2019] linux - How does cat EOF work in bash - Stack Overflow

Notable quotes:
"... The $sql variable now holds the new-line characters too. You can verify with echo -e "$sql" . ..."
"... The print.sh file now contains: ..."
"... The b.txt file contains bar and baz lines. The same output is printed to stdout . ..."
Jan 10, 2019 | stackoverflow.com

How does "cat << EOF" work in bash? Ask Question 454


hasen ,Mar 23, 2010 at 13:57

I needed to write a script to enter multi-line input to a program ( psql ).

After a bit of googling, I found the following syntax works:

cat << EOF | psql ---params
BEGIN;

`pg_dump ----something`

update table .... statement ...;

END;
EOF

This correctly constructs the multi-line string (from BEGIN; to END; , inclusive) and pipes it as an input to psql .

But I have no idea how/why it works, can some one please explain?

I'm referring mainly to cat << EOF , I know > outputs to a file, >> appends to a file, < reads input from file.

What does << exactly do?

And is there a man page for it?

Dennis Williamson ,Mar 23, 2010 at 18:28

That's probably a useless use of cat . Try psql ... << EOF ... See also "here strings". mywiki.wooledge.org/BashGuide/InputAndOutput?#Here_StringsDennis Williamson Mar 23 '10 at 18:28

hasen ,Mar 23, 2010 at 18:54

@Dennis: good point, and thanks for the link! – hasen Mar 23 '10 at 18:54

Alex ,Mar 23, 2015 at 23:31

I'm surprised it works with cat but not with echo. cat should expect a file name as stdin, not a char string. psql << EOF sounds logical, but not othewise. Works with cat but not with echo. Strange behaviour. Any clue about that? – Alex Mar 23 '15 at 23:31

Alex ,Mar 23, 2015 at 23:39

Answering to myself: cat without parameters executes and replicates to the output whatever send via input (stdin), hence using its output to fill the file via >. In fact a file name read as a parameter is not a stdin stream. – Alex Mar 23 '15 at 23:39

The-null-Pointer- ,Jan 1, 2018 at 18:03

@Alex echo just prints it's command line arguments while cat reads stding(when piped to it) or reads a file that corresponds to it's command line args – The-null-Pointer- Jan 1 '18 at 18:03

kennytm ,Mar 23, 2010 at 13:58

This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.

From man bash :

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen.

All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word . If any characters in word are quoted, the delimiter is the result of quote removal on word , and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \ , $ , and ` .

If the redirection operator is <<- , then all leading tab characters are stripped from input lines and the line containing delimiter . This allows here-documents within shell scripts to be indented in a natural fashion.

Xeoncross ,May 26, 2011 at 22:51

I was having the hardest time disabling variable/parameter expansion. All I needed to do was use "double-quotes" and that fixed it! Thanks for the info! – Xeoncross May 26 '11 at 22:51

trkoch ,Nov 10, 2015 at 17:23

Concerning <<- please note that only leading tab characters are stripped -- not soft tab characters. This is one of those rare case when you actually need the tab character. If the rest of your document uses soft tabs, make sure to show invisible characters and (e.g.) copy and paste a tab character. If you do it right, your syntax highlighting should correctly catch the ending delimiter. – trkoch Nov 10 '15 at 17:23

BrDaHa ,Jul 13, 2017 at 19:01

I don't see how this answer is more helpful than the ones below. It merely regurgitates information that can be found in other places (that have likely already been checked) – BrDaHa Jul 13 '17 at 19:01

Vojtech Vitek ,Feb 4, 2014 at 10:28

The cat <<EOF syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe. Examples of cat <<EOF syntax usage in Bash: 1. Assign multi-line string to a shell variable
$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

The $sql variable now holds the new-line characters too. You can verify with echo -e "$sql" .

2. Pass multi-line string to a file in Bash
$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

The print.sh file now contains:

#!/bin/bash
echo $PWD
echo /home/user
3. Pass multi-line string to a pipe in Bash
$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

The b.txt file contains bar and baz lines. The same output is printed to stdout .

edelans ,Aug 22, 2014 at 8:48

In your case, "EOF" is known as a "Here Tag". Basically <<Here tells the shell that you are going to enter a multiline string until the "tag" Here . You can name this tag as you want, it's often EOF or STOP .

Some rules about the Here tags:

  1. The tag can be any string, uppercase or lowercase, though most people use uppercase by convention.
  2. The tag will not be considered as a Here tag if there are other words in that line. In this case, it will merely be considered part of the string. The tag should be by itself on a separate line, to be considered a tag.
  3. The tag should have no leading or trailing spaces in that line to be considered a tag. Otherwise it will be considered as part of the string.

example:

$ cat >> test <<HERE
> Hello world HERE <-- Not by itself on a separate line -> not considered end of string
> This is a test
>  HERE <-- Leading space, so not considered end of string
> and a new line
> HERE <-- Now we have the end of the string

oemb1905 ,Feb 22, 2017 at 7:17

this is the best actual answer ... you define both and clearly state the primary purpose of the use instead of related theory ... which is important but not necessary ... thanks - super helpful – oemb1905 Feb 22 '17 at 7:17

The-null-Pointer- ,Jan 1, 2018 at 18:05

@edelans you must add that when <<- is used leading tab will not prevent the tag from being recognized – The-null-Pointer- Jan 1 '18 at 18:05

JawSaw ,Oct 28, 2018 at 13:44

your answer clicked me on "you are going to enter a multiline string" – JawSaw Oct 28 '18 at 13:44

Ciro Santilli 新疆改造中心 六四事件 法轮功 ,Jun 9, 2015 at 9:41

POSIX 7

kennytm quoted man bash , but most of that is also POSIX 7: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04 :

The redirection operators "<<" and "<<-" both allow redirection of lines contained in a shell input file, known as a "here-document", to the input of a command.

The here-document shall be treated as a single word that begins after the next and continues until there is a line containing only the delimiter and a , with no characters in between. Then the next here-document starts, if there is one. The format is as follows:

[n]<<word
    here-document
delimiter

where the optional n represents the file descriptor number. If the number is omitted, the here-document refers to standard input (file descriptor 0).

If any character in word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.

If no characters in word are quoted, all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion. In this case, the in the input behaves as the inside double-quotes (see Double-Quotes). However, the double-quote character ( '"' ) shall not be treated specially within a here-document, except when the double-quote appears within "$()", "``", or "${}".

If the redirection symbol is "<<-", all leading <tab> characters shall be stripped from input lines and the line containing the trailing delimiter. If more than one "<<" or "<<-" operator is specified on a line, the here-document associated with the first operator shall be supplied first by the application and shall be read first by the shell.

When a here-document is read from a terminal device and the shell is interactive, it shall write the contents of the variable PS2, processed as described in Shell Variables, to standard error before reading each line of input until the delimiter has been recognized.

Examples

Some examples not yet given.

Quotes prevent parameter expansion

Without quotes:

a=0
cat <<EOF
$a
EOF

Output:

0

With quotes:

a=0
cat <<'EOF'
$a
EOF

or (ugly but valid):

a=0
cat <<E"O"F
$a
EOF

Outputs:

$a
Hyphen removes leading tabs

Without hyphen:

cat <<EOF
<tab>a
EOF

where <tab> is a literal tab, and can be inserted with Ctrl + V <tab>

Output:

<tab>a

With hyphen:

cat <<-EOF
<tab>a
<tab>EOF

Output:

a

This exists of course so that you can indent your cat like the surrounding code, which is easier to read and maintain. E.g.:

if true; then
    cat <<-EOF
    a
    EOF
fi

Unfortunately, this does not work for space characters: POSIX favored tab indentation here. Yikes.

David C. Rankin ,Aug 12, 2015 at 7:10

In your last example discussing <<- and <tab>a , it should be noted that the purpose was to allow normal indentation of code within the script while allowing heredoc text presented to the receiving process to begin in column 0. It is a not too commonly seen feature and a bit more context may prevent a good deal of head-scratching... – David C. Rankin Aug 12 '15 at 7:10

Ciro Santilli 新疆改造中心 六四事件 法轮功 ,Aug 12, 2015 at 8:22

@DavidC.Rankin updated to clarify that, thanks. – Ciro Santilli 新疆改造中心 六四事件 法轮功 Aug 12 '15 at 8:22

Jeanmichel Cote ,Sep 23, 2015 at 19:58

How should i escape expension if some of the content in between my EOF tags needs to be expanded and some don't? – Jeanmichel Cote Sep 23 '15 at 19:58

Jeanmichel Cote ,Sep 23, 2015 at 20:00

...just use the backslash in front of the $Jeanmichel Cote Sep 23 '15 at 20:00

Ciro Santilli 新疆改造中心 六四事件 法轮功 ,Sep 23, 2015 at 20:01

@JeanmichelCote I don't see a better option :-) With regular strings you can also consider mixing up quotes like "$a"'$b'"$c" , but there is no analogue here AFAIK. – Ciro Santilli 新疆改造中心 六四事件 法轮功 Sep 23 '15 at 20:01

Andreas Maier ,Feb 13, 2017 at 12:14

Using tee instead of cat

Not exactly as an answer to the original question, but I wanted to share this anyway: I had the need to create a config file in a directory that required root rights.

The following does not work for that case:

$ sudo cat <<EOF >/etc/somedir/foo.conf
# my config file
foo=bar
EOF

because the redirection is handled outside of the sudo context.

I ended up using this instead:

$ sudo tee <<EOF /etc/somedir/foo.conf >/dev/null
# my config file
foo=bar
EOF

user9048395

add a comment ,Jun 6, 2018 at 0:15
This isn't necessarily an answer to the original question, but a sharing of some results from my own testing. This:
<<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test

will produce the same file as:

cat <<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test

So, I don't see the point of using the cat command.

> ,Dec 19, 2013 at 21:40

Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:
export postgres_db_name='my_db'
export table_name='my_table_name'

# start copy 
while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_schema = 'public'
AND table_name   =:'table_name'  ;
EOF
)
# stop copy , now paste straight into the bash shell ...

output: 
my_table_name.guid ,
my_table_name.id ,
my_table_name.level ,
my_table_name.seq ,

or even without the new line

while read -r c; do test -z "$c" || echo $table_name.$c , | perl -ne 
's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
 SELECT column_name
 FROM information_schema.columns
 WHERE 1=1
 AND table_schema = 'public'
 AND table_name   =:'table_name'  ;
 EOF
 )

 # output: daily_issues.guid ,daily_issues.id ,daily_issues.level ,daily_issues.seq ,daily_issues.prio ,daily_issues.weight ,daily_issues.status ,daily_issues.category ,daily_issues.name ,daily_issues.description ,daily_issues.type ,daily_issues.owner

[Dec 23, 2018] Founder of LiveJournal doesn't know the definition of "ennui"

Dec 23, 2018 | hexmode.com

That is all . (Ok, so I realize some of you will need some more information. Brad Fitzpatrick, with Danga and now SixApart, is pretty amazing when it comes to the software he's developed and released to the public . These range from utilities to provide secure backups on hardware you don't own ( brackup ) distributed job schedulers (The Schwartz) and others I've written about . Note for you Perl-bashers that he did much of this in Perl.)

[Dec 16, 2018] What are the benefits using Docker?

Dec 16, 2018 | www.quora.com

The main benefit of Docker is that it automatically solves the problems with versioning and cross-platform deployment, as the images can be easily recombined to form any version and can run in any environment where Docker is installed. "Run anywhere" meme...


James Lee , former Software Engineer at Google (2013-2016) Answered Jul 12 · Author has 106 answers and 258.1k answer views

There are many beneifits of Docker. Firstly, I would mention the beneifits of Docker and then let you know about the future of Docker. The content mentioned here is from my recent article on Docker.

Docker Beneifits:

Docker is an open-source project based on Linux containers. It uses the features based on the Linux Kernel. For example, namespaces and control groups create containers. But are containers new? No, Google has been using it for years! They have their own container technology. There are some other Linux container technologies like Solaris Zones, LXC, etc.

These container technologies are already there before Docker came into existence. Then why Docker? What difference did it make? Why is it on the rise? Ok, I will tell you why!

Number 1: Docker offers ease of use

Taking advantage of containers wasn't an easy task with earlier technologies. Docker has made it easy for everyone like developers, system admins, architects, and more. Test portable applications are easy to build. Anyone can package an application from their laptop. He/She can then run it unmodified on any public/private cloud or bare metal. The slogan is, "build once, run anywhere"!

Number 2: Docker offers speed

Being lightweight, the containers are fast. They also consume fewer resources. One can easily run a Docker container in seconds. On the other side, virtual machines usually take longer as they go through the whole process of booting up the complete virtual operating system, every time!

Number 3: The Docker Hub

Docker offers an ecosystem known as the Docker Hub. You can consider it as an app store for Docker images. It contains many public images created by the community. These images are ready to use. You can easily search the images as per your requirements.

Number 4: Docker gives modularity and scalability

It is possible to break down the application functionality into individual containers. Docker gives this freedom! It is easy to link containers together and create your application with Docker. One can easily scale and update components independently in the future.

The Future

A lot of people come and ask me that "Will Docker eat up virtual machines?" I don't think so! Docker is gaining a lot of momentum but this won't affect virtual machines. This reason is that virtual machines are better under certain circumstances as compared to Docker. For example, if there is a requirement of running multiple applications on multiple servers, then virtual machines is a better choice. On the contrary, if there is a requirement to run multiple copies of a single application, Docker is a better choice.

Docker containers could create a problem when it comes to security because containers share the same kernel. The barriers between containers are quite thin. But I do believe that security and management improve with experience and exposure. Docker certainly has a great future! I hope that this Docker tutorial has helped you understand the basics of Containers, VM's, and Dockers. But Docker in itself is an ocean. It isn't possible to study Docker in just one article. For an in-depth study of Docker, I recommend this Docker course.

Please feel free to Like/Subscribe/Comment on my YouTube Videos/Channel mentioned below :

David Polstra , Person at ReactiveOps (2016-present) Updated Oct 5, 2017 · Author has 65 answers and 53.7k answer views

I work at Re