Hello smturner1,

I am trying to understand how this subroutine works and I just cannot workout the logic.

Despite the various missing pieces ($ARCHIVE, $SourceDir, @errors, ...), the general logic of the subroutine is fairly straightforward. The aim is to populate an array, @diffs, with details of the differences between the two directories $ARCHIVE and $SourceDir. First, the contents of $ARCHIVE are stored as keys in the hash %old_list, and the contents of $SourceDir are stored as keys in the hash %new_list. With this information available, it is then easy to determine which files are present in $ARCHIVE but not in $SourceDir:

for my $file (sort keys %old_list) { if ( !defined $new_list{$file} ) { push @diffs, "Old file not in new: $file"; } }

This tests each filename in %old_list and looks for it in %new_list. And this code reveals the reason for storing filenames as hash keys rather than as array elements: it is much simpler to test whether a key is present in a hash using defined than to search through an array. Incidentally, the call to sort is pointless here, and exists is usually preferable to defined in this situation.

In a similar manner, the next for loop identifies those files which are present in $SourceDir but absent from $ARCHIVE.

The specifically “Perlish” aspect to this code is the elegant use of hashes to search through lists. See, for example, How can I tell whether a certain element is contained in a list or array?

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: Comparing files in directory by Athanasius
in thread Comparing files in directory by smturner1

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.