{
    "mode": "perldoc",
    "parameter": "diff",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/diff/json",
    "generated": "2026-06-03T04:23:14Z",
    "sections": {
        "Found in /usr/share/perl/5.34/pod/perlfaq1.pod": {
            "content": "Is Perl difficult to learn?\nNo, Perl is easy to start learning <http://learn.perl.org/> --and easy\nto keep learning. It looks like most programming languages you're likely\nto have experience with, so if you've ever written a C program, an awk\nscript, a shell script, or even a BASIC program, you're already partway\nthere.\n\nMost tasks only require a small subset of the Perl language. One of the\nguiding mottos for Perl development is \"there's more than one way to do\nit\" (TMTOWTDI, sometimes pronounced \"tim toady\"). Perl's learning curve\nis therefore shallow (easy to learn) and long (there's a whole lot you\ncan do if you really want).\n\nFinally, because Perl is frequently (but not always, and certainly not\nby definition) an interpreted language, you can write your programs and\ntest them without an intermediate compilation step, allowing you to\nexperiment and test/debug quickly and easily. This ease of\nexperimentation flattens the learning curve even more.\n\nThings that make Perl easier to learn: Unix experience, almost any kind\nof programming experience, an understanding of regular expressions, and\nthe ability to understand other people's code. If there's something you\nneed to do, then it's probably already been done, and a working example\nis usually available for free. Don't forget Perl modules, either.\nThey're discussed in Part 3 of this FAQ, along with CPAN\n<http://www.cpan.org/>, which is discussed in Part 2.\n\nWhat's the difference between \"perl\" and \"Perl\"?\n\"Perl\" is the name of the language. Only the \"P\" is capitalized. The\nname of the interpreter (the program which runs the Perl script) is\n\"perl\" with a lowercase \"p\".\n\nYou may or may not choose to follow this usage. But never write \"PERL\",\nbecause perl is not an acronym.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq4.pod": {
            "content": "How can I compare two dates and find the difference?\n(contributed by brian d foy)\n\nYou could just store all your dates as a number and then subtract. Life\nisn't always that simple though.\n\nThe Time::Piece module, which comes with Perl, replaces localtime with a\nversion that returns an object. It also overloads the comparison\noperators so you can compare them directly:\n\nuse Time::Piece;\nmy $date1 = localtime( $sometime );\nmy $date2 = localtime( $someothertime );\n\nif( $date1 < $date2 ) {\nprint \"The date was in the past\\n\";\n}\n\nYou can also get differences with a subtraction, which returns a\nTime::Seconds object:\n\nmy $datediff = $date1 - $date2;\nprint \"The difference is \", $datediff->days, \" days\\n\";\n\nIf you want to work with formatted dates, the Date::Manip, Date::Calc,\nor DateTime modules can help you.\n\nWhat is the difference between a list and an array?\n(contributed by brian d foy)\n\nA list is a fixed collection of scalars. An array is a variable that\nholds a variable collection of scalars. An array can supply its\ncollection for list operations, so list operations also work on arrays:\n\n# slices\n( 'dog', 'cat', 'bird' )[2,3];\n@animals[2,3];\n\n# iteration\nforeach ( qw( dog cat bird ) ) { ... }\nforeach ( @animals ) { ... }\n\nmy @three = grep { length == 3 } qw( dog cat bird );\nmy @three = grep { length == 3 } @animals;\n\n# supply an argument list\nwashanimals( qw( dog cat bird ) );\nwashanimals( @animals );\n\nArray operations, which change the scalars, rearrange them, or add or\nsubtract some scalars, only work on arrays. These can't work on a list,\nwhich is fixed. Array operations include \"shift\", \"unshift\", \"push\",\n\"pop\", and \"splice\".\n\nAn array can also change its length:\n\n$#animals = 1;  # truncate to two elements\n$#animals = 10000; # pre-extend to 10,001 elements\n\nYou can change an array element, but you can't change a list element:\n\n$animals[0] = 'Rottweiler';\nqw( dog cat bird )[0] = 'Rottweiler'; # syntax error!\n\nforeach ( @animals ) {\ns/^d/fr/;  # works fine\n}\n\nforeach ( qw( dog cat bird ) ) {\ns/^d/fr/;  # Error! Modification of read only value!\n}\n\nHowever, if the list element is itself a variable, it appears that you\ncan change a list element. However, the list element is the variable,\nnot the data. You're not changing the list element, but something the\nlist element refers to. The list element itself doesn't change: it's\nstill the same variable.\n\nYou also have to be careful about context. You can assign an array to a\nscalar to get the number of elements in the array. This only works for\narrays, though:\n\nmy $count = @animals;  # only works with arrays\n\nIf you try to do the same thing with what you think is a list, you get a\nquite different result. Although it looks like you have a list on the\nrighthand side, Perl actually sees a bunch of scalars separated by a\ncomma:\n\nmy $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird\n\nSince you're assigning to a scalar, the righthand side is in scalar\ncontext. The comma operator (yes, it's an operator!) in scalar context\nevaluates its lefthand side, throws away the result, and evaluates it's\nrighthand side and returns the result. In effect, that list-lookalike\nassigns to $scalar it's rightmost value. Many people mess this up\nbecause they choose a list-lookalike whose last element is also the\ncount they expect:\n\nmy $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally\n\nWhat is the difference between $array[1] and @array[1]?\n(contributed by brian d foy)\n\nThe difference is the sigil, that special character in front of the\narray name. The \"$\" sigil means \"exactly one item\", while the \"@\" sigil\nmeans \"zero or more items\". The \"$\" gets you a single scalar, while the\n\"@\" gets you a list.\n\nThe confusion arises because people incorrectly assume that the sigil\ndenotes the variable type.\n\nThe $array[1] is a single-element access to the array. It's going to\nreturn the item in index 1 (or undef if there is no item there). If you\nintend to get exactly one element from the array, this is the form you\nshould use.\n\nThe @array[1] is an array slice, although it has only one index. You can\npull out multiple elements simultaneously by specifying additional\nindices as a list, like @array[1,4,3,0].\n\nUsing a slice on the lefthand side of the assignment supplies list\ncontext to the righthand side. This can lead to unexpected results. For\ninstance, if you want to read a single line from a filehandle, assigning\nto a scalar value is fine:\n\n$array[1] = <STDIN>;\n\nHowever, in list context, the line input operator returns all of the\nlines as a list. The first line goes into @array[1] and the rest of the\nlines mysteriously disappear:\n\n@array[1] = <STDIN>;  # most likely not what you want\n\nEither the \"use warnings\" pragma or the -w flag will warn you when you\nuse an array slice with a single index.\n\nHow do I compute the difference of two arrays? How do I compute the intersection of two arrays?\nUse a hash. Here's code to do both and more. It assumes that each\nelement is unique in a given array:\n\nmy (@union, @intersection, @difference);\nmy %count = ();\nforeach my $element (@array1, @array2) { $count{$element}++ }\nforeach my $element (keys %count) {\npush @union, $element;\npush @{ $count{$element} > 1 ? \\@intersection : \\@difference }, $element;\n}\n\nNote that this is the *symmetric difference*, that is, all elements in\neither A or in B but not in both. Think of it as an xor operation.\n\nWhat's the difference between \"delete\" and \"undef\" with hashes?\nHashes contain pairs of scalars: the first is the key, the second is the\nvalue. The key will be coerced to a string, although the value can be\nany kind of scalar: string, number, or reference. If a key $key is\npresent in %hash, \"exists($hash{$key})\" will return true. The value for\na given key can be \"undef\", in which case $hash{$key} will be \"undef\"\nwhile \"exists $hash{$key}\" will return true. This corresponds to ($key,\n\"undef\") being in the hash.\n\nPictures help... Here's the %hash table:\n\nkeys  values\n+------+------+\n|  a   |  3   |\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nAnd these conditions hold\n\n$hash{'a'}                       is true\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is true\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nIf you now say\n\nundef $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  a   | undef|\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is FALSE\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is FALSE\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nNotice the last two: you have an undef value, but a defined key!\n\nNow, consider this:\n\ndelete $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is false\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is false\nexists $hash{'a'}                is FALSE (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is FALSE\n\nSee, the whole entry is gone!\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq6.pod": {
            "content": "How can I pull out lines between two patterns that are themselves on different lines?\nYou can use Perl's somewhat exotic \"..\" operator (documented in perlop):\n\nperl -ne 'print if /START/ .. /END/' file1 file2 ...\n\nIf you wanted text and not lines, you would use\n\nperl -0777 -ne 'print \"$1\\n\" while /START(.*?)END/gs' file1 file2 ...\n\nBut if you want nested occurrences of \"START\" through \"END\", you'll run\nup against the problem described in the question in this section on\nmatching balanced text.\n\nHere's another example of using \"..\":\n\nwhile (<>) {\nmy $inheader =   1  .. /^$/;\nmy $inbody   = /^$/ .. eof;\n# now choose between them\n} continue {\n$. = 0 if eof;    # fix $.\n}\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq7.pod": {
            "content": "Why do Perl operators have different precedence than C operators?\nActually, they don't. All C operators that Perl copies have the same\nprecedence in Perl as they do in C. The problem is with operators that C\ndoesn't have, especially functions that give a list context to\neverything on their right, eg. print, chmod, exec, and so on. Such\nfunctions are called \"list operators\" and appear as such in the\nprecedence table in perlop.\n\nA common mistake is to write:\n\nunlink $file || die \"snafu\";\n\nThis gets interpreted as:\n\nunlink ($file || die \"snafu\");\n\nTo avoid this problem, either put in extra parentheses or use the super\nlow precedence \"or\" operator:\n\n(unlink $file) || die \"snafu\";\nunlink $file or die \"snafu\";\n\nThe \"English\" operators (\"and\", \"or\", \"xor\", and \"not\") deliberately\nhave precedence lower than that of list operators for just such\nsituations as the one above.\n\nAnother operator with surprising precedence is exponentiation. It binds\nmore tightly even than unary minus, making \"-22\" produce a negative\nfour and not a positive one. It is also right-associating, meaning that\n\"232\" is two raised to the ninth power, not eight squared.\n\nAlthough it has the same precedence as in C, Perl's \"?:\" operator\nproduces an lvalue. This assigns $x to either $iftrue or $iffalse,\ndepending on the trueness of $maybe:\n\n($maybe ? $iftrue : $iffalse) = $x;\n\nWhat's the difference between dynamic and lexical (static) scoping? Between local() and my()?\n\"local($x)\" saves away the old value of the global variable $x and\nassigns a new value for the duration of the subroutine *which is visible\nin other functions called from that subroutine*. This is done at\nrun-time, so is called dynamic scoping. local() always affects global\nvariables, also called package variables or dynamic variables.\n\n\"my($x)\" creates a new variable that is only visible in the current\nsubroutine. This is done at compile-time, so it is called lexical or\nstatic scoping. my() always affects private variables, also called\nlexical variables or (improperly) static(ly scoped) variables.\n\nFor instance:\n\nsub visible {\nprint \"var has value $var\\n\";\n}\n\nsub dynamic {\nlocal $var = 'local';    # new temporary value for the still-global\nvisible();              #   variable called $var\n}\n\nsub lexical {\nmy $var = 'private';    # new private variable, $var\nvisible();              # (invisible outside of sub scope)\n}\n\n$var = 'global';\n\nvisible();              # prints global\ndynamic();              # prints local\nlexical();              # prints global\n\nNotice how at no point does the value \"private\" get printed. That's\nbecause $var only has that value within the block of the lexical()\nfunction, and it is hidden from the called subroutine.\n\nIn summary, local() doesn't make what you think of as private, local\nvariables. It gives a global variable a temporary value. my() is what\nyou're looking for if you want private variables.\n\nSee \"Private Variables via my()\" in perlsub and \"Temporary Values via",
            "subsections": [
                {
                    "name": "local",
                    "content": "What's the difference between deep and shallow binding?\nIn deep binding, lexical variables mentioned in anonymous subroutines\nare the same ones that were in scope when the subroutine was created. In\nshallow binding, they are whichever variables with the same names happen\nto be in scope when the subroutine is called. Perl always uses deep\nbinding of lexical variables (i.e., those created with my()). However,\ndynamic variables (aka global, local, or package variables) are\neffectively shallowly bound. Consider this just one more reason not to\nuse them. See the answer to \"What's a closure?\".\n\nWhat's the difference between calling a function as &foo and foo()?\n(contributed by brian d foy)\n\nCalling a subroutine as &foo with no trailing parentheses ignores the\nprototype of \"foo\" and passes it the current value of the argument list,\n@. Here's an example; the \"bar\" subroutine calls &foo, which prints its\narguments list:\n\nsub foo { print \"Args in foo are: @\\n\"; }\n\nsub bar { &foo; }\n\nbar( \"a\", \"b\", \"c\" );\n\nWhen you call \"bar\" with arguments, you see that \"foo\" got the same @:\n\nArgs in foo are: a b c\n\nCalling the subroutine with trailing parentheses, with or without\narguments, does not use the current @. Changing the example to put\nparentheses after the call to \"foo\" changes the program:\n\nsub foo { print \"Args in foo are: @\\n\"; }\n\nsub bar { &foo(); }\n\nbar( \"a\", \"b\", \"c\" );\n\nNow the output shows that \"foo\" doesn't get the @ from its caller.\n\nArgs in foo are:\n\nHowever, using \"&\" in the call still overrides the prototype of \"foo\" if\npresent:\n\nsub foo ($$$) { print \"Args infoo are: @\\n\"; }\n\nsub bar1 { &foo; }\nsub bar2 { &foo(); }\nsub bar3 { foo( $[0], $[1], $[2] ); }\n# sub bar4 { foo(); }\n# bar4 doesn't compile: \"Not enough arguments for main::foo at ...\"\n\nbar1( \"a\", \"b\", \"c\" );\n# Args in foo are: a b c\n\nbar2( \"a\", \"b\", \"c\" );\n# Args in foo are:\n\nbar3( \"a\", \"b\", \"c\" );\n# Args in foo are: a b c\n\nThe main use of the @ pass-through feature is to write subroutines\nwhose main job it is to call other subroutines for you. For further\ndetails, see perlsub.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq8.pod": {
            "content": "How do I tell the difference between errors from the shell and perl?\n(answer contributed by brian d foy)\n\nWhen you run a Perl script, something else is running the script for\nyou, and that something else may output error messages. The script might\nemit its own warnings and error messages. Most of the time you cannot\ntell who said what.\n\nYou probably cannot fix the thing that runs perl, but you can change how\nperl outputs its warnings by defining a custom warning and die\nfunctions.\n\nConsider this script, which has an error you may not notice immediately.\n\n#!/usr/locl/bin/perl\n\nprint \"Hello World\\n\";\n\nI get an error when I run this from my shell (which happens to be bash).\nThat may look like perl forgot it has a \"print()\" function, but my\nshebang line is not the path to perl, so the shell runs the script, and\nI get the error.\n\n$ ./test\n./test: line 3: print: command not found\n\nA quick and dirty fix involves a little bit of code, but this may be all\nyou need to figure out the problem.\n\n#!/usr/bin/perl -w\n\nBEGIN {\n$SIG{WARN} = sub{ print STDERR \"Perl: \", @; };\n$SIG{DIE}  = sub{ print STDERR \"Perl: \", @; exit 1};\n}\n\n$a = 1 + undef;\n$x / 0;\nEND\n\nThe perl message comes out with \"Perl\" in front. The \"BEGIN\" block works\nat compile time so all of the compilation errors and warnings get the\n\"Perl:\" prefix too.\n\nPerl: Useless use of division (/) in void context at ./test line 9.\nPerl: Name \"main::a\" used only once: possible typo at ./test line 8.\nPerl: Name \"main::x\" used only once: possible typo at ./test line 9.\nPerl: Use of uninitialized value in addition (+) at ./test line 8.\nPerl: Use of uninitialized value in division (/) at ./test line 9.\nPerl: Illegal division by zero at ./test line 9.\nPerl: Illegal division by zero at -e line 3.\n\nIf I don't see that \"Perl:\", it's not from perl.\n\nYou could also just know all the perl errors, and although there are\nsome people who may know all of them, you probably don't. However, they\nall should be in the perldiag manpage. If you don't find the error in\nthere, it probably isn't a perl error.\n\nLooking up every message is not the easiest way, so let perl to do it\nfor you. Use the diagnostics pragma with turns perl's normal messages\ninto longer discussions on the topic.\n\nuse diagnostics;\n\nIf you don't get a paragraph or two of expanded discussion, it might not\nbe perl's message.\n\nWhat's the difference between require and use?\n(contributed by brian d foy)\n\nPerl runs \"require\" statement at run-time. Once Perl loads, compiles,\nand runs the file, it doesn't do anything else. The \"use\" statement is\nthe same as a \"require\" run at compile-time, but Perl also calls the\n\"import\" method for the loaded package. These two are the same:\n\nuse MODULE qw(import list);\n\nBEGIN {\nrequire MODULE;\nMODULE->import(import list);\n}\n\nHowever, you can suppress the \"import\" by using an explicit, empty\nimport list. Both of these still happen at compile-time:\n\nuse MODULE ();\n\nBEGIN {\nrequire MODULE;\n}\n\nSince \"use\" will also call the \"import\" method, the actual value for\n\"MODULE\" must be a bareword. That is, \"use\" cannot load files by name,\nalthough \"require\" can:\n\nrequire \"$ENV{HOME}/lib/Foo.pm\"; # no @INC searching!\n\nSee the entry for \"use\" in perlfunc for more details.\n",
            "subsections": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": [],
    "tldr": {
        "source": "official",
        "description": "Compare files and directories.",
        "examples": [
            {
                "description": "Compare files (lists changes to turn `old_file` into `new_file`)",
                "command": "diff {{path/to/old_file}} {{path/to/new_file}}"
            },
            {
                "description": "Compare files, ignoring white spaces",
                "command": "diff {{-w|--ignore-all-space}} {{path/to/old_file}} {{path/to/new_file}}"
            },
            {
                "description": "Compare files, showing the differences side by side",
                "command": "diff {{-y|--side-by-side}} {{path/to/old_file}} {{path/to/new_file}}"
            },
            {
                "description": "Compare files, showing the differences in unified format (as used by `git diff`)",
                "command": "diff {{-u|--unified}} {{path/to/old_file}} {{path/to/new_file}}"
            },
            {
                "description": "Compare directories recursively (shows names for differing files/directories as well as changes made to files)",
                "command": "diff {{-r|--recursive}} {{path/to/old_directory}} {{path/to/new_directory}}"
            },
            {
                "description": "Compare directories, only showing the names of files that differ",
                "command": "diff {{-r|--recursive}} {{-q|--brief}} {{path/to/old_directory}} {{path/to/new_directory}}"
            },
            {
                "description": "Create a patch file for Git from the differences of two text files, treating nonexistent files as empty",
                "command": "diff {{-a|--text}} {{-u|--unified}} {{-N|--new-file}} {{path/to/old_file}} {{path/to/new_file}} > {{path/to/diff.patch}}"
            },
            {
                "description": "Compare files, showing output in color, trying hard to find the smallest set of changes",
                "command": "diff {{-d|--minimal}} --color=always {{path/to/old_file}} {{path/to/new_file}}"
            }
        ]
    }
}