{
    "mode": "man",
    "parameter": "perlintro",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlintro/1/json",
    "generated": "2026-08-24T06:14:36Z",
    "sections": {
        "NAME": {
            "content": "perlintro - a brief introduction and overview of Perl\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This document is intended to give you a quick overview of the Perl programming language,\nalong with pointers to further documentation.  It is intended as a \"bootstrap\" guide for\nthose who are new to the language, and provides just enough information for you to be able to\nread other peoples' Perl and understand roughly what it's doing, or write your own simple\nscripts.\n\nThis introductory document does not aim to be complete.  It does not even aim to be entirely\naccurate.  In some cases perfection has been sacrificed in the goal of getting the general\nidea across.  You are strongly advised to follow this introduction with more information from\nthe full Perl manual, the table of contents to which can be found in perltoc.\n\nThroughout this document you'll see references to other parts of the Perl documentation.  You\ncan read that documentation using the \"perldoc\" command or whatever method you're using to\nread this document.\n\nThroughout Perl's documentation, you'll find numerous examples intended to help explain the\ndiscussed features.  Please keep in mind that many of them are code fragments rather than\ncomplete programs.\n\nThese examples often reflect the style and preference of the author of that piece of the\ndocumentation, and may be briefer than a corresponding line of code in a real program.\nExcept where otherwise noted, you should assume that \"use strict\" and \"use warnings\"\nstatements appear earlier in the \"program\", and that any variables used have already been\ndeclared, even if those declarations have been omitted to make the example easier to read.\n\nDo note that the examples have been written by many different authors over a period of\nseveral decades.  Styles and techniques will therefore differ, although some effort has been\nmade to not vary styles too widely in the same sections.  Do not consider one style to be\nbetter than others - \"There's More Than One Way To Do It\" is one of Perl's mottos.  After\nall, in your journey as a programmer, you are likely to encounter different styles.\n",
            "subsections": [
                {
                    "name": "What is Perl?",
                    "content": "Perl is a general-purpose programming language originally developed for text manipulation and\nnow used for a wide range of tasks including system administration, web development, network\nprogramming, GUI development, and more.\n\nThe language is intended to be practical (easy to use, efficient, complete) rather than\nbeautiful (tiny, elegant, minimal).  Its major features are that it's easy to use, supports\nboth procedural and object-oriented (OO) programming, has powerful built-in support for text\nprocessing, and has one of the world's most impressive collections of third-party modules.\n\nDifferent definitions of Perl are given in perl, perlfaq1 and no doubt other places.  From\nthis we can determine that Perl is different things to different people, but that lots of\npeople think it's at least worth writing about.\n"
                },
                {
                    "name": "Running Perl programs",
                    "content": "To run a Perl program from the Unix command line:\n\nperl progname.pl\n\nAlternatively, put this as the first line of your script:\n\n#!/usr/bin/env perl\n\n... and run the script as /path/to/script.pl.  Of course, it'll need to be executable first,\nso \"chmod 755 script.pl\" (under Unix).\n\n(This start line assumes you have the env program.  You can also put directly the path to\nyour perl executable, like in \"#!/usr/bin/perl\").\n\nFor more information, including instructions for other platforms such as Windows, read\nperlrun.\n"
                },
                {
                    "name": "Safety net",
                    "content": "Perl by default is very forgiving.  In order to make it more robust it is recommended to\nstart every program with the following lines:\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nThe two additional lines request from perl to catch various common problems in your code.\nThey check different things so you need both.  A potential problem caught by \"use strict;\"\nwill cause your code to stop immediately when it is encountered, while \"use warnings;\" will\nmerely give a warning (like the command-line switch -w) and let your code run.  To read more\nabout them, check their respective manual pages at strict and warnings.\n\nA \"use v5.35\" (or higher) declaration will enable both \"strict\" and \"warnings\":\n\n#!/usr/bin/perl\nuse v5.35;\n\nIn addition to enabling the \"strict\" and \"warnings\" pragmata, this declaration will also\nactivate a \"feature bundle\"; a collection of named features that enable many of the more\nrecent additions and changes to the language, as well as occasionally removing older features\nfound to have been mistakes in design and discouraged.\n"
                },
                {
                    "name": "Basic syntax overview",
                    "content": "A Perl script or program consists of one or more statements.  These statements are simply\nwritten in the script in a straightforward fashion.  There is no need to have a main()\nfunction or anything of that kind.\n\nPerl statements end in a semi-colon:\n\nprint \"Hello, world\";\n\nComments start with a hash symbol and run to the end of the line\n\n# This is a comment\n\nWhitespace is irrelevant:\n\nprint\n\"Hello, world\"\n;\n\n... except inside quoted strings:\n\n# this would print with a linebreak in the middle\nprint \"Hello\nworld\";\n\nDouble quotes or single quotes may be used around literal strings:\n\nprint \"Hello, world\";\nprint 'Hello, world';\n\nHowever, only double quotes \"interpolate\" variables and special characters such as newlines\n(\"\\n\"):\n\nprint \"Hello, $name\\n\";     # works fine\nprint 'Hello, $name\\n';     # prints $name\\n literally\n\nNumbers don't need quotes around them:\n\nprint 42;\n\nYou can use parentheses for functions' arguments or omit them according to your personal\ntaste.  They are only required occasionally to clarify issues of precedence.\n\nprint(\"Hello, world\\n\");\nprint \"Hello, world\\n\";\n\nMore detailed information about Perl syntax can be found in perlsyn.\n"
                },
                {
                    "name": "Perl variable types",
                    "content": "Perl has three main variable types: scalars, arrays, and hashes.\n\nScalars\nA scalar represents a single value:\n\nmy $animal = \"camel\";\nmy $answer = 42;\n\nScalar  values  can  be  strings,  integers  or  floating  point  numbers,  and Perl will\nautomatically convert between them as required.  You have to declare them using the  \"my\"\nkeyword the first time you use them.  (This is one of the requirements of \"use strict;\".)\n\nScalar values can be used in various ways:\n\nprint $animal;\nprint \"The animal is $animal\\n\";\nprint \"The square of $answer is \", $answer * $answer, \"\\n\";\n\nPerl defines a number of special scalars with short names, often single punctuation marks\nor  digits.  These  variables  are  used for all kinds of purposes, and are documented in\nperlvar.  The only one you need to know about  for  now  is  $  which  is  the  \"default\nvariable\".   It's used as the default argument to a number of functions in Perl, and it's\nset implicitly by certain looping constructs.\n\nprint;          # prints contents of $ by default\n\nArrays\nAn array represents a list of values:\n\nmy @animals = (\"camel\", \"llama\", \"owl\");\nmy @numbers = (23, 42, 69);\nmy @mixed   = (\"camel\", 42, 1.23);\n\nArrays are zero-indexed.  Here's how you get at elements in an array:\n\nprint $animals[0];              # prints \"camel\"\nprint $animals[1];              # prints \"llama\"\n\nThe special variable $#array tells you the index of the last element of an array:\n\nprint $mixed[$#mixed];       # last element, prints 1.23\n\nYou might be tempted to use \"$#array + 1\" to tell you how many  items  there  are  in  an\narray.   Don't  bother.   As it happens, using @array where Perl expects to find a scalar\nvalue (\"in scalar context\") will give you the number of elements in the array:\n\nif (@animals < 5) { ... }\n\nThe elements we're getting from the array start with a \"$\" because we're getting  just  a\nsingle value out of the array; you ask for a scalar, you get a scalar.\n\nTo get multiple values from an array:\n\n@animals[0,1];                 # gives (\"camel\", \"llama\");\n@animals[0..2];                # gives (\"camel\", \"llama\", \"owl\");\n@animals[1..$#animals];        # gives all except the first element\n\nThis is called an \"array slice\".\n\nYou can do various useful things to lists:\n\nmy @sorted    = sort @animals;\nmy @backwards = reverse @numbers;\n\nThere  are  a  couple of special arrays too, such as @ARGV (the command line arguments to\nyour script) and @ (the arguments passed to a  subroutine).   These  are  documented  in\nperlvar.\n\nHashes\nA hash represents a set of key/value pairs:\n\nmy %fruitcolor = (\"apple\", \"red\", \"banana\", \"yellow\");\n\nYou can use whitespace and the \"=>\" operator to lay them out more nicely:\n\nmy %fruitcolor = (\napple  => \"red\",\nbanana => \"yellow\",\n);\n\nTo get at hash elements:\n\n$fruitcolor{\"apple\"};           # gives \"red\"\n\nYou can get at lists of keys and values with keys() and values().\n\nmy @fruits = keys %fruitcolor;\nmy @colors = values %fruitcolor;\n\nHashes  have  no particular internal order, though you can sort the keys and loop through\nthem.\n\nJust like special scalars and arrays, there are also special hashes.  The most well known\nof these is %ENV which contains environment variables.  Read  all  about  it  (and  other\nspecial variables) in perlvar.\n\nScalars, arrays and hashes are documented more fully in perldata.\n\nMore  complex  data types can be constructed using references, which allow you to build lists\nand hashes within lists and hashes.\n\nA reference is a scalar value and can refer to any other Perl data type.   So  by  storing  a\nreference  as  the  value of an array or hash element, you can easily create lists and hashes\nwithin lists and hashes.  The following example shows a 2 level hash of hash structure  using\nanonymous hash references.\n\nmy $variables = {\nscalar  =>  {\ndescription => \"single item\",\nsigil => '$',\n},\narray   =>  {\ndescription => \"ordered list of items\",\nsigil => '@',\n},\nhash    =>  {\ndescription => \"key/value pairs\",\nsigil => '%',\n},\n};\n\nprint \"Scalars begin with a $variables->{'scalar'}->{'sigil'}\\n\";\n\nExhaustive  information  on  the  topic  of  references  can be found in perlreftut, perllol,\nperlref and perldsc.\n"
                },
                {
                    "name": "Variable scoping",
                    "content": "Throughout the previous section all the examples have used the syntax:\n\nmy $var = \"value\";\n\nThe \"my\" is actually not required; you could just use:\n\n$var = \"value\";\n\nHowever, the above usage will create global variables throughout your program, which  is  bad\nprogramming  practice.   \"my\"  creates lexically scoped variables instead.  The variables are\nscoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are\ndefined.\n\nmy $x = \"foo\";\nmy $somecondition = 1;\nif ($somecondition) {\nmy $y = \"bar\";\nprint $x;           # prints \"foo\"\nprint $y;           # prints \"bar\"\n}\nprint $x;               # prints \"foo\"\nprint $y;               # prints nothing; $y has fallen out of scope\n\nUsing \"my\" in combination with a \"use strict;\" at the top of your Perl scripts means that the\ninterpreter will pick up certain common programming errors.  For  instance,  in  the  example\nabove, the final \"print $y\" would cause a compile-time error and prevent you from running the\nprogram.  Using \"strict\" is highly recommended.\n"
                },
                {
                    "name": "Conditional and looping constructs",
                    "content": "Perl has most of the usual conditional and looping constructs.\n\nThe conditions can be any Perl expression.  See the list of operators in the next section for\ninformation on comparison and boolean logic operators, which are commonly used in conditional\nstatements.\n\nif\nif ( condition ) {\n...\n} elsif ( other condition ) {\n...\n} else {\n...\n}\n\nThere's also a negated version of it:\n\nunless ( condition ) {\n...\n}\n\nThis is provided as a more readable version of \"if (!condition)\".\n\nNote that the braces are required in Perl, even if you've only got one line in the block.\nHowever,  there  is  a clever way of making your one-line conditional blocks more English\nlike:\n\n# the traditional way\nif ($zippy) {\nprint \"Yow!\";\n}\n\n# the Perlish post-condition way\nprint \"Yow!\" if $zippy;\nprint \"We have no bananas\" unless $bananas;\n\nwhile\nwhile ( condition ) {\n...\n}\n\nThere's also a negated version, for the same reason we have \"unless\":\n\nuntil ( condition ) {\n...\n}\n\nYou can also use \"while\" in a post-condition:\n\nprint \"LA LA LA\\n\" while 1;          # loops forever\n\nfor Exactly like C:\n\nfor ($i = 0; $i <= $max; $i++) {\n...\n}\n\nThe C style for loop is rarely needed in Perl since Perl provides the more friendly  list\nscanning \"foreach\" loop.\n\nforeach\nforeach (@array) {\nprint \"This element is $\\n\";\n}\n\nprint $list[$] foreach 0 .. $max;\n\n# you don't have to use the default $ either...\nforeach my $key (keys %hash) {\nprint \"The value of $key is $hash{$key}\\n\";\n}\n\nThe  \"foreach\" keyword is actually a synonym for the \"for\" keyword.  See \"\"Foreach Loops\"\nin perlsyn\".\n\nFor more detail on looping constructs (and some that weren't mentioned in this overview)  see\nperlsyn.\n"
                },
                {
                    "name": "Builtin operators and functions",
                    "content": "Perl  comes  with a wide selection of builtin functions.  Some of the ones we've already seen\ninclude \"print\", \"sort\" and \"reverse\".  A list of them is given at the start of perlfunc  and\nyou can easily read about any given function by using \"perldoc -f functionname\".\n\nPerl operators are documented in full in perlop, but here are a few of the most common ones:\n\nArithmetic\n+   addition\n-   subtraction\n*   multiplication\n/   division\n\nNumeric comparison\n==  equality\n!=  inequality\n<   less than\n>   greater than\n<=  less than or equal\n>=  greater than or equal\n\nString comparison\neq  equality\nne  inequality\nlt  less than\ngt  greater than\nle  less than or equal\nge  greater than or equal\n\n(Why  do  we have separate numeric and string comparisons?  Because we don't have special\nvariable types, and Perl needs to know whether to sort numerically (where 99 is less than\n100) or alphabetically (where 100 comes before 99).\n\nBoolean logic\n&&  and\n||  or\n!   not\n\n(\"and\", \"or\" and \"not\" aren't just in the above table as descriptions of  the  operators.\nThey're  also  supported as operators in their own right.  They're more readable than the\nC-style operators, but have different precedence to \"&&\" and friends.  Check  perlop  for\nmore detail.)\n\nMiscellaneous\n=   assignment\n.   string concatenation\nx   string multiplication (repeats strings)\n..  range operator (creates a list of numbers or strings)\n\nMany operators can be combined with a \"=\" as follows:\n\n$a += 1;        # same as $a = $a + 1\n$a -= 1;        # same as $a = $a - 1\n$a .= \"\\n\";     # same as $a = $a . \"\\n\";\n"
                },
                {
                    "name": "Files and I/O",
                    "content": "You  can  open  a  file  for  input  or output using the open() function.  It's documented in\nextravagant detail in perlfunc and perlopentut, but in short:\n\nopen(my $in,  \"<\",  \"input.txt\")  or die \"Can't open input.txt: $!\";\nopen(my $out, \">\",  \"output.txt\") or die \"Can't open output.txt: $!\";\nopen(my $log, \">>\", \"my.log\")     or die \"Can't open my.log: $!\";\n\nYou can read from an open filehandle using the \"<>\" operator.  In scalar context it  reads  a\nsingle  line  from  the filehandle, and in list context it reads the whole file in, assigning\neach line to an element of the list:\n\nmy $line  = <$in>;\nmy @lines = <$in>;\n\nReading in the whole file at one time is called slurping.  It can be useful but it may  be  a\nmemory  hog.   Most  text  file  processing  can be done a line at a time with Perl's looping\nconstructs.\n\nThe \"<>\" operator is most often seen in a \"while\" loop:\n\nwhile (<$in>) {     # assigns each line in turn to $\nprint \"Just read in this line: $\";\n}\n\nWe've already seen how to print to standard output using print().  However, print() can  also\ntake an optional first argument specifying which filehandle to print to:\n\nprint STDERR \"This is your final warning.\\n\";\nprint $out $record;\nprint $log $logmessage;\n\nWhen  you're  done  with your filehandles, you should close() them (though to be honest, Perl\nwill clean up after you if you forget):\n\nclose $in or die \"$in: $!\";\n"
                },
                {
                    "name": "Regular expressions",
                    "content": "Perl's regular expression support is both broad and deep,  and  is  the  subject  of  lengthy\ndocumentation in perlrequick, perlretut, and elsewhere.  However, in short:\n\nSimple matching\nif (/foo/)       { ... }  # true if $ contains \"foo\"\nif ($a =~ /foo/) { ... }  # true if $a contains \"foo\"\n\nThe \"//\" matching operator is documented in perlop.  It operates on $ by default, or can\nbe bound to another variable using the \"=~\" binding operator (also documented in perlop).\n\nSimple substitution\ns/foo/bar/;               # replaces foo with bar in $\n$a =~ s/foo/bar/;         # replaces foo with bar in $a\n$a =~ s/foo/bar/g;        # replaces ALL INSTANCES of foo with bar\n# in $a\n\nThe \"s///\" substitution operator is documented in perlop.\n\nMore complex regular expressions\nYou  don't  just  have  to  match on fixed strings.  In fact, you can match on just about\nanything you could dream of  by  using  more  complex  regular  expressions.   These  are\ndocumented at great length in perlre, but for the meantime, here's a quick cheat sheet:\n\n.                   a single character\n\\s                  a whitespace character (space, tab, newline,\n...)\n\\S                  non-whitespace character\n\\d                  a digit (0-9)\n\\D                  a non-digit\n\\w                  a word character (a-z, A-Z, 0-9, )\n\\W                  a non-word character\n[aeiou]             matches a single character in the given set\n[^aeiou]            matches a single character outside the given\nset\n(foo|bar|baz)       matches any of the alternatives specified\n\n^                   start of string\n$                   end of string\n\nQuantifiers  can  be used to specify how many of the previous thing you want to match on,\nwhere \"thing\" means either a literal character, one of the metacharacters  listed  above,\nor a group of characters or metacharacters in parentheses.\n\n*                   zero or more of the previous thing\n+                   one or more of the previous thing\n?                   zero or one of the previous thing\n{3}                 matches exactly 3 of the previous thing\n{3,6}               matches between 3 and 6 of the previous thing\n{3,}                matches 3 or more of the previous thing\n\nSome brief examples:\n\n/^\\d+/              string starts with one or more digits\n/^$/                nothing in the string (start and end are\nadjacent)\n/(\\d\\s){3}/         three digits, each followed by a whitespace\ncharacter (eg \"3 4 5 \")\n/(a.)+/             matches a string in which every odd-numbered\nletter is a (eg \"abacadaf\")\n\n# This loop reads from STDIN, and prints non-blank lines:\nwhile (<>) {\nnext if /^$/;\nprint;\n}\n\nParentheses for capturing\nAs well as grouping, parentheses serve a second purpose.  They can be used to capture the\nresults  of parts of the regexp match for later use.  The results end up in $1, $2 and so\non.\n\n# a cheap and nasty way to break an email address up into parts\n\nif ($email =~ /([^@]+)@(.+)/) {\nprint \"Username is $1\\n\";\nprint \"Hostname is $2\\n\";\n}\n\nOther regexp features\nPerl regexps also support backreferences, lookaheads, and  all  kinds  of  other  complex\ndetails.  Read all about them in perlrequick, perlretut, and perlre.\n"
                },
                {
                    "name": "Writing subroutines",
                    "content": "Writing subroutines is easy:\n\nsub logger {\nmy $logmessage = shift;\nopen my $logfile, \">>\", \"my.log\" or die \"Could not open my.log: $!\";\nprint $logfile $logmessage;\n}\n\nNow we can use the subroutine just as any other built-in function:\n\nlogger(\"We have a logger subroutine!\");\n\nWhat's  that  \"shift\"?   Well, the arguments to a subroutine are available to us as a special\narray called @ (see perlvar for more on that).  The default argument to the \"shift\" function\njust happens to be @.  So \"my $logmessage = shift;\" shifts the first item off  the  list  of\narguments and assigns it to $logmessage.\n\nWe can manipulate @ in other ways too:\n\nmy ($logmessage, $priority) = @;       # common\nmy $logmessage = $[0];                 # uncommon, and ugly\n\nSubroutines can also return values:\n\nsub square {\nmy $num = shift;\nmy $result = $num * $num;\nreturn $result;\n}\n\nThen use it like:\n\n$sq = square(8);\n\nFor more information on writing subroutines, see perlsub.\n"
                },
                {
                    "name": "OO Perl",
                    "content": "OO  Perl  is  relatively  simple  and is implemented using references which know what sort of\nobject they are based on Perl's concept of packages.  However, OO Perl is largely beyond  the\nscope of this document.  Read perlootut and perlobj.\n\nAs  a beginning Perl programmer, your most common use of OO Perl will be in using third-party\nmodules, which are documented below.\n"
                },
                {
                    "name": "Using Perl modules",
                    "content": "Perl modules provide a range of features to help you avoid reinventing the wheel, and can  be\ndownloaded  from  CPAN  ( <http://www.cpan.org/> ).  A number of popular modules are included\nwith the Perl distribution itself.\n\nCategories of  modules  range  from  text  manipulation  to  network  protocols  to  database\nintegration to graphics.  A categorized list of modules is also available from CPAN.\n\nTo learn how to install modules you download from CPAN, read perlmodinstall.\n\nTo learn how to use a particular module, use \"perldoc Module::Name\".  Typically you will want\nto  \"use  Module::Name\",  which  will  then  give  you  access to exported functions or an OO\ninterface to the module.\n\nperlfaq contains questions and answers related to  many  common  tasks,  and  often  provides\nsuggestions for good CPAN modules to use.\n\nperlmod describes Perl modules in general.  perlmodlib lists the modules which came with your\nPerl installation.\n\nIf you feel the urge to write Perl modules, perlnewmod will give you good advice.\n"
                }
            ]
        },
        "AUTHOR": {
            "content": "Kirrily \"Skud\" Robert <skud@cpan.org>\n\nperl v5.38.2                                 2026-06-12                                 PERLINTRO(1)",
            "subsections": []
        }
    },
    "summary": "perlintro - a brief introduction and overview of Perl",
    "flags": [],
    "examples": [],
    "see_also": []
}