faneesh has asked for the wisdom of the Perl Monks concerning the following question:

HI
I am new to Perl and want to know if there is difference in below declaration
Type 1:

my $filename=sprintf("%s/filename1.log.%s",$file_dir,$todayDate);

Type 2:

my $filename="${file_dir}/filename1.log.${today_date}";

I know both declarations will work, but want to know which is good practice and if there is any reason for the same.
Thanks in advance.

Replies are listed 'Best First'.
Re: string concatenation, which way is better?
by trizen (Hermit) on Aug 08, 2012 at 21:27 UTC
    Both are good, but if you concatenate files and want to make your code portable, I recommend the File::Spec::Functions module.

    Something like this:
    use File::Spec::Functions qw(catfile); my $filename = catfile($file_dir, q{filename1.log.} . $today_date);

    Back on the topic. The following codes are equivalent:
    1. $this . q{/} . $that
    2. join(q{/}, $this, $that)
    3. "$this/$hat"
    4. do{local $"=q{/}; "@{[$this, $that]}"}
    5. sprintf('%s/%s', $this, $that)

    Most used are: 1, 2, 3.
Re: string concatenation, which way is better?
by frozenwithjoy (Priest) on Aug 08, 2012 at 21:39 UTC
    Personally, I've found the following approach to be more readable and easier to maintain:
    my $filename = $file_dir . "/filename1.log." . $today_date;
    However, if you don't like the concatenation operator for some reason, you can just go with:
    my $filename = "$file_dir/filename1.log.$today_date";
Re: string concatenation, which way is better?
by johngg (Canon) on Aug 08, 2012 at 22:09 UTC

    You seem to be a little inconsistent with your variable names between the two code examples, $todayDate in one and $today_date in the other, so you may have a typo in your script. I don't know how you initialise your $todayDate variable. If you generate it programmatically in your code rather than reading it from a file you may find the strftime() function of the POSIX module along with localtime and time useful.

    $ perl -MPOSIX=strftime -E ' > $file_dir = q{/var/log}; > say strftime qq{$file_dir/filename1.log.%F}, localtime( time() );' /var/log/filename1.log.2012-08-08 $

    I hope this is helpful.

    Cheers,

    JohnGG

Re: string concatenation, which way is better?
by BillKSmith (Monsignor) on Aug 09, 2012 at 02:50 UTC
    Concatination is needed to break up a long line.
    my $filename = $file_dir . "/filename1.log." . $today_date ;
Re: string concatenation, which way is better?
by Anonymous Monk on Aug 09, 2012 at 00:35 UTC
    In this case it probably makes little difference; it's a matter of personal preference. In the general case you sometimes need the exact-formatting control that sprintf() provides. Depends on the circumstances.