diff(1) - perldoc - phpman

Look up a command

 

Markdown Format | JSON API | MCP Server Tool


TLDR: diff (tldr-pages)

Compare files and directories.

  • Compare files (lists changes to turn `old_file` into `new_file`)
    diff {{path/to/old_file}} {{path/to/new_file}}
  • Compare files, ignoring white spaces
    diff {{-w|--ignore-all-space}} {{path/to/old_file}} {{path/to/new_file}}
  • Compare files, showing the differences side by side
    diff {{-y|--side-by-side}} {{path/to/old_file}} {{path/to/new_file}}
  • Compare files, showing the differences in unified format (as used by `git diff`)
    diff {{-u|--unified}} {{path/to/old_file}} {{path/to/new_file}}
  • Compare directories recursively (shows names for differing files/directories as well as changes made to files)
    diff {{-r|--recursive}} {{path/to/old_directory}} {{path/to/new_directory}}
  • Compare directories, only showing the names of files that differ
    diff {{-r|--recursive}} {{-q|--brief}} {{path/to/old_directory}} {{path/to/new_directory}}
  • Create a patch file for Git from the differences of two text files, treating nonexistent files as empty
    diff {{-a|--text}} {{-u|--unified}} {{-N|--new-file}} {{path/to/old_file}} {{path/to/new_file}} > {{path/to/diff.patch}}
  • Compare files, showing output in color, trying hard to find the smallest set of changes
    diff {{-d|--minimal}} --color=always {{path/to/old_file}} {{path/to/new_file}}
diff(1)
Found in /usr/share/perl/5.34/pod/perlfaq1.pod Found in /usr/share/perl/5.34/pod/perlfaq4.pod Found in /usr/share/perl/5.34/pod/perlfaq6.pod Found in /usr/share/perl/5.34/pod/perlfaq7.pod Found in /usr/share/perl/5.34/pod/perlfaq8.pod
Found in /usr/share/perl/5.34/pod/perlfaq1.pod
  Is Perl difficult to learn?
    No, Perl is easy to start learning <http://learn.perl.org/> --and easy
    to keep learning. It looks like most programming languages you're likely
    to have experience with, so if you've ever written a C program, an awk
    script, a shell script, or even a BASIC program, you're already partway
    there.

    Most tasks only require a small subset of the Perl language. One of the
    guiding mottos for Perl development is "there's more than one way to do
    it" (TMTOWTDI, sometimes pronounced "tim toady"). Perl's learning curve
    is therefore shallow (easy to learn) and long (there's a whole lot you
    can do if you really want).

    Finally, because Perl is frequently (but not always, and certainly not
    by definition) an interpreted language, you can write your programs and
    test them without an intermediate compilation step, allowing you to
    experiment and test/debug quickly and easily. This ease of
    experimentation flattens the learning curve even more.

    Things that make Perl easier to learn: Unix experience, almost any kind
    of programming experience, an understanding of regular expressions, and
    the ability to understand other people's code. If there's something you
    need to do, then it's probably already been done, and a working example
    is usually available for free. Don't forget Perl modules, either.
    They're discussed in Part 3 of this FAQ, along with CPAN
    <http://www.cpan.org/>, which is discussed in Part 2.

  What's the difference between "perl" and "Perl"?
    "Perl" is the name of the language. Only the "P" is capitalized. The
    name of the interpreter (the program which runs the Perl script) is
    "perl" with a lowercase "p".

    You may or may not choose to follow this usage. But never write "PERL",
    because perl is not an acronym.

Found in /usr/share/perl/5.34/pod/perlfaq4.pod
  How can I compare two dates and find the difference?
    (contributed by brian d foy)

    You could just store all your dates as a number and then subtract. Life
    isn't always that simple though.

    The Time::Piece module, which comes with Perl, replaces localtime with a
    version that returns an object. It also overloads the comparison
    operators so you can compare them directly:

        use Time::Piece;
        my $date1 = localtime( $some_time );
        my $date2 = localtime( $some_other_time );

        if( $date1 < $date2 ) {
            print "The date was in the past\n";
        }

    You can also get differences with a subtraction, which returns a
    Time::Seconds object:

        my $date_diff = $date1 - $date2;
        print "The difference is ", $date_diff->days, " days\n";

    If you want to work with formatted dates, the Date::Manip, Date::Calc,
    or DateTime modules can help you.

  What is the difference between a list and an array?
    (contributed by brian d foy)

    A list is a fixed collection of scalars. An array is a variable that
    holds a variable collection of scalars. An array can supply its
    collection for list operations, so list operations also work on arrays:

        # slices
        ( 'dog', 'cat', 'bird' )[2,3];
        @animals[2,3];

        # iteration
        foreach ( qw( dog cat bird ) ) { ... }
        foreach ( @animals ) { ... }

        my @three = grep { length == 3 } qw( dog cat bird );
        my @three = grep { length == 3 } @animals;

        # supply an argument list
        wash_animals( qw( dog cat bird ) );
        wash_animals( @animals );

    Array operations, which change the scalars, rearrange them, or add or
    subtract some scalars, only work on arrays. These can't work on a list,
    which is fixed. Array operations include "shift", "unshift", "push",
    "pop", and "splice".

    An array can also change its length:

        $#animals = 1;  # truncate to two elements
        $#animals = 10000; # pre-extend to 10,001 elements

    You can change an array element, but you can't change a list element:

        $animals[0] = 'Rottweiler';
        qw( dog cat bird )[0] = 'Rottweiler'; # syntax error!

        foreach ( @animals ) {
            s/^d/fr/;  # works fine
        }

        foreach ( qw( dog cat bird ) ) {
            s/^d/fr/;  # Error! Modification of read only value!
        }

    However, if the list element is itself a variable, it appears that you
    can change a list element. However, the list element is the variable,
    not the data. You're not changing the list element, but something the
    list element refers to. The list element itself doesn't change: it's
    still the same variable.

    You also have to be careful about context. You can assign an array to a
    scalar to get the number of elements in the array. This only works for
    arrays, though:

        my $count = @animals;  # only works with arrays

    If you try to do the same thing with what you think is a list, you get a
    quite different result. Although it looks like you have a list on the
    righthand side, Perl actually sees a bunch of scalars separated by a
    comma:

        my $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird

    Since you're assigning to a scalar, the righthand side is in scalar
    context. The comma operator (yes, it's an operator!) in scalar context
    evaluates its lefthand side, throws away the result, and evaluates it's
    righthand side and returns the result. In effect, that list-lookalike
    assigns to $scalar it's rightmost value. Many people mess this up
    because they choose a list-lookalike whose last element is also the
    count they expect:

        my $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally

  What is the difference between $array[1] and @array[1]?
    (contributed by brian d foy)

    The difference is the sigil, that special character in front of the
    array name. The "$" sigil means "exactly one item", while the "@" sigil
    means "zero or more items". The "$" gets you a single scalar, while the
    "@" gets you a list.

    The confusion arises because people incorrectly assume that the sigil
    denotes the variable type.

    The $array[1] is a single-element access to the array. It's going to
    return the item in index 1 (or undef if there is no item there). If you
    intend to get exactly one element from the array, this is the form you
    should use.

    The @array[1] is an array slice, although it has only one index. You can
    pull out multiple elements simultaneously by specifying additional
    indices as a list, like @array[1,4,3,0].

    Using a slice on the lefthand side of the assignment supplies list
    context to the righthand side. This can lead to unexpected results. For
    instance, if you want to read a single line from a filehandle, assigning
    to a scalar value is fine:

        $array[1] = <STDIN>;

    However, in list context, the line input operator returns all of the
    lines as a list. The first line goes into @array[1] and the rest of the
    lines mysteriously disappear:

        @array[1] = <STDIN>;  # most likely not what you want

    Either the "use warnings" pragma or the -w flag will warn you when you
    use an array slice with a single index.

  How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
    Use a hash. Here's code to do both and more. It assumes that each
    element is unique in a given array:

        my (@union, @intersection, @difference);
        my %count = ();
        foreach my $element (@array1, @array2) { $count{$element}++ }
        foreach my $element (keys %count) {
            push @union, $element;
            push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
        }

    Note that this is the *symmetric difference*, that is, all elements in
    either A or in B but not in both. Think of it as an xor operation.

  What's the difference between "delete" and "undef" with hashes?
    Hashes contain pairs of scalars: the first is the key, the second is the
    value. The key will be coerced to a string, although the value can be
    any kind of scalar: string, number, or reference. If a key $key is
    present in %hash, "exists($hash{$key})" will return true. The value for
    a given key can be "undef", in which case $hash{$key} will be "undef"
    while "exists $hash{$key}" will return true. This corresponds to ($key,
    "undef") being in the hash.

    Pictures help... Here's the %hash table:

          keys  values
        +------+------+
        |  a   |  3   |
        |  x   |  7   |
        |  d   |  0   |
        |  e   |  2   |
        +------+------+

    And these conditions hold

        $hash{'a'}                       is true
        $hash{'d'}                       is false
        defined $hash{'d'}               is true
        defined $hash{'a'}               is true
        exists $hash{'a'}                is true (Perl 5 only)
        grep ($_ eq 'a', keys %hash)     is true

    If you now say

        undef $hash{'a'}

    your table now reads:

          keys  values
        +------+------+
        |  a   | undef|
        |  x   |  7   |
        |  d   |  0   |
        |  e   |  2   |
        +------+------+

    and these conditions now hold; changes in caps:

        $hash{'a'}                       is FALSE
        $hash{'d'}                       is false
        defined $hash{'d'}               is true
        defined $hash{'a'}               is FALSE
        exists $hash{'a'}                is true (Perl 5 only)
        grep ($_ eq 'a', keys %hash)     is true

    Notice the last two: you have an undef value, but a defined key!

    Now, consider this:

        delete $hash{'a'}

    your table now reads:

          keys  values
        +------+------+
        |  x   |  7   |
        |  d   |  0   |
        |  e   |  2   |
        +------+------+

    and these conditions now hold; changes in caps:

        $hash{'a'}                       is false
        $hash{'d'}                       is false
        defined $hash{'d'}               is true
        defined $hash{'a'}               is false
        exists $hash{'a'}                is FALSE (Perl 5 only)
        grep ($_ eq 'a', keys %hash)     is FALSE

    See, the whole entry is gone!

Found in /usr/share/perl/5.34/pod/perlfaq6.pod
  How can I pull out lines between two patterns that are themselves on different lines?
    You can use Perl's somewhat exotic ".." operator (documented in perlop):

        perl -ne 'print if /START/ .. /END/' file1 file2 ...

    If you wanted text and not lines, you would use

        perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...

    But if you want nested occurrences of "START" through "END", you'll run
    up against the problem described in the question in this section on
    matching balanced text.

    Here's another example of using "..":

        while (<>) {
            my $in_header =   1  .. /^$/;
            my $in_body   = /^$/ .. eof;
        # now choose between them
        } continue {
            $. = 0 if eof;    # fix $.
        }

Found in /usr/share/perl/5.34/pod/perlfaq7.pod
  Why do Perl operators have different precedence than C operators?
    Actually, they don't. All C operators that Perl copies have the same
    precedence in Perl as they do in C. The problem is with operators that C
    doesn't have, especially functions that give a list context to
    everything on their right, eg. print, chmod, exec, and so on. Such
    functions are called "list operators" and appear as such in the
    precedence table in perlop.

    A common mistake is to write:

        unlink $file || die "snafu";

    This gets interpreted as:

        unlink ($file || die "snafu");

    To avoid this problem, either put in extra parentheses or use the super
    low precedence "or" operator:

        (unlink $file) || die "snafu";
        unlink $file or die "snafu";

    The "English" operators ("and", "or", "xor", and "not") deliberately
    have precedence lower than that of list operators for just such
    situations as the one above.

    Another operator with surprising precedence is exponentiation. It binds
    more tightly even than unary minus, making "-2**2" produce a negative
    four and not a positive one. It is also right-associating, meaning that
    "2**3**2" is two raised to the ninth power, not eight squared.

    Although it has the same precedence as in C, Perl's "?:" operator
    produces an lvalue. This assigns $x to either $if_true or $if_false,
    depending on the trueness of $maybe:

        ($maybe ? $if_true : $if_false) = $x;

  What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
    "local($x)" saves away the old value of the global variable $x and
    assigns a new value for the duration of the subroutine *which is visible
    in other functions called from that subroutine*. This is done at
    run-time, so is called dynamic scoping. local() always affects global
    variables, also called package variables or dynamic variables.

    "my($x)" creates a new variable that is only visible in the current
    subroutine. This is done at compile-time, so it is called lexical or
    static scoping. my() always affects private variables, also called
    lexical variables or (improperly) static(ly scoped) variables.

    For instance:

        sub visible {
            print "var has value $var\n";
        }

        sub dynamic {
            local $var = 'local';    # new temporary value for the still-global
            visible();              #   variable called $var
        }

        sub lexical {
            my $var = 'private';    # new private variable, $var
            visible();              # (invisible outside of sub scope)
        }

        $var = 'global';

        visible();              # prints global
        dynamic();              # prints local
        lexical();              # prints global

    Notice how at no point does the value "private" get printed. That's
    because $var only has that value within the block of the lexical()
    function, and it is hidden from the called subroutine.

    In summary, local() doesn't make what you think of as private, local
    variables. It gives a global variable a temporary value. my() is what
    you're looking for if you want private variables.

    See "Private Variables via my()" in perlsub and "Temporary Values via
    local()" in perlsub for excruciating details.

  What's the difference between deep and shallow binding?
    In deep binding, lexical variables mentioned in anonymous subroutines
    are the same ones that were in scope when the subroutine was created. In
    shallow binding, they are whichever variables with the same names happen
    to be in scope when the subroutine is called. Perl always uses deep
    binding of lexical variables (i.e., those created with my()). However,
    dynamic variables (aka global, local, or package variables) are
    effectively shallowly bound. Consider this just one more reason not to
    use them. See the answer to "What's a closure?".

  What's the difference between calling a function as &foo and foo()?
    (contributed by brian d foy)

    Calling a subroutine as &foo with no trailing parentheses ignores the
    prototype of "foo" and passes it the current value of the argument list,
    @_. Here's an example; the "bar" subroutine calls &foo, which prints its
    arguments list:

        sub foo { print "Args in foo are: @_\n"; }

        sub bar { &foo; }

        bar( "a", "b", "c" );

    When you call "bar" with arguments, you see that "foo" got the same @_:

        Args in foo are: a b c

    Calling the subroutine with trailing parentheses, with or without
    arguments, does not use the current @_. Changing the example to put
    parentheses after the call to "foo" changes the program:

        sub foo { print "Args in foo are: @_\n"; }

        sub bar { &foo(); }

        bar( "a", "b", "c" );

    Now the output shows that "foo" doesn't get the @_ from its caller.

        Args in foo are:

    However, using "&" in the call still overrides the prototype of "foo" if
    present:

        sub foo ($$$) { print "Args infoo are: @_\n"; }

        sub bar_1 { &foo; }
        sub bar_2 { &foo(); }
        sub bar_3 { foo( $_[0], $_[1], $_[2] ); }
        # sub bar_4 { foo(); }
        # bar_4 doesn't compile: "Not enough arguments for main::foo at ..."

        bar_1( "a", "b", "c" );
        # Args in foo are: a b c

        bar_2( "a", "b", "c" );
        # Args in foo are:

        bar_3( "a", "b", "c" );
        # Args in foo are: a b c

    The main use of the @_ pass-through feature is to write subroutines
    whose main job it is to call other subroutines for you. For further
    details, see perlsub.

Found in /usr/share/perl/5.34/pod/perlfaq8.pod
  How do I tell the difference between errors from the shell and perl?
    (answer contributed by brian d foy)

    When you run a Perl script, something else is running the script for
    you, and that something else may output error messages. The script might
    emit its own warnings and error messages. Most of the time you cannot
    tell who said what.

    You probably cannot fix the thing that runs perl, but you can change how
    perl outputs its warnings by defining a custom warning and die
    functions.

    Consider this script, which has an error you may not notice immediately.

        #!/usr/locl/bin/perl

        print "Hello World\n";

    I get an error when I run this from my shell (which happens to be bash).
    That may look like perl forgot it has a "print()" function, but my
    shebang line is not the path to perl, so the shell runs the script, and
    I get the error.

        $ ./test
        ./test: line 3: print: command not found

    A quick and dirty fix involves a little bit of code, but this may be all
    you need to figure out the problem.

        #!/usr/bin/perl -w

        BEGIN {
            $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
            $SIG{__DIE__}  = sub{ print STDERR "Perl: ", @_; exit 1};
        }

        $a = 1 + undef;
        $x / 0;
        __END__

    The perl message comes out with "Perl" in front. The "BEGIN" block works
    at compile time so all of the compilation errors and warnings get the
    "Perl:" prefix too.

        Perl: Useless use of division (/) in void context at ./test line 9.
        Perl: Name "main::a" used only once: possible typo at ./test line 8.
        Perl: Name "main::x" used only once: possible typo at ./test line 9.
        Perl: Use of uninitialized value in addition (+) at ./test line 8.
        Perl: Use of uninitialized value in division (/) at ./test line 9.
        Perl: Illegal division by zero at ./test line 9.
        Perl: Illegal division by zero at -e line 3.

    If I don't see that "Perl:", it's not from perl.

    You could also just know all the perl errors, and although there are
    some people who may know all of them, you probably don't. However, they
    all should be in the perldiag manpage. If you don't find the error in
    there, it probably isn't a perl error.

    Looking up every message is not the easiest way, so let perl to do it
    for you. Use the diagnostics pragma with turns perl's normal messages
    into longer discussions on the topic.

        use diagnostics;

    If you don't get a paragraph or two of expanded discussion, it might not
    be perl's message.

  What's the difference between require and use?
    (contributed by brian d foy)

    Perl runs "require" statement at run-time. Once Perl loads, compiles,
    and runs the file, it doesn't do anything else. The "use" statement is
    the same as a "require" run at compile-time, but Perl also calls the
    "import" method for the loaded package. These two are the same:

        use MODULE qw(import list);

        BEGIN {
            require MODULE;
            MODULE->import(import list);
        }

    However, you can suppress the "import" by using an explicit, empty
    import list. Both of these still happen at compile-time:

        use MODULE ();

        BEGIN {
            require MODULE;
        }

    Since "use" will also call the "import" method, the actual value for
    "MODULE" must be a bareword. That is, "use" cannot load files by name,
    although "require" can:

        require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!

    See the entry for "use" in perlfunc for more details.


Generated by phpMan Author: Che Dong Under GNU General Public License
2026-06-02 18:35 @216.73.216.151 CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 TransitionalValid CSS!

^_back to top