Other people have pointed you to File::Spec->catfile: that's the way to do it for portable code (e.g. something you expect to post to CPAN).

What I do for local, unix-only hackery is: I never include a trailing slash on directories, and always build up new paths with double-quoted strings.

A typical script might look something like this:

use Env qw( $HOME ); use File::Path qw( mkpath ); use File::Basename qw( basename dirname fileparse ); use File::Copy qw( move copy ); my $some_file = shift; my $basename = basename( $some_file ); my $backup_location = "$HOME/backups"; mkpath( $backup_location ) unless -d $backup_location; my $new_file = "$backup_location/$basename.bak"; copy("$some_file", "$new_file") or die "got problems: $!";

My personal opinion is that doing things like this is a win for readability:
my $new_file = "$backup_location/$basename.bak";

Also, note the stack of "use"s at the top... it's hard to do anything The Right Way in perl without leaning on the standard library a lot. These days I use script templates that include a dozen "use"s by default, so I don't have to try to remember what module "fileparse" is hidden inside of, and so on.


In reply to Re: How do monks create paths? by doom
in thread How do monks create paths? by Cody Pendant

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.