http://www.perlmonks.org?node_id=1008416

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

Hello All, I'm trying to create a string to ultimately copy a file from one location to the other, but when i try to append a common string to the end of the file I'm not getting the results that I expect. Each file suffix is -vda.img with the prefix all completely random. Here is what I have so far..

$OLDVMDIR = "/sunstorage_kvm_images/kvm_images/images"; #Current Dire +ctory $NEWVMDIR = "/sunstorage_kvm_images/kvm_images/images_new"; #Target ( +New) Directory $VMSFX = "\-vda\.img"; #File suffix for each file <snip> @VMSHUT = `cat /tmp/virshlist_shutdown`; foreach $VMSHUT (@VMSHUT) { $VMFILE = $OLDVMDIR . $VMSHUT . $VMSFX; print "$VMFILE $NEWVMDIR \n"; }

What I'm expecting is it to print something like this..

/sunstorage_kvm_images/kvm_images/images/Debian-vda.img /sunstorage_kvm_images/kvm_images/images_new

Instead I'm getting..

/sunstorage_kvm_images/kvm_images/imagesDebian

-vda.img /sunstorage_kvm_images/kvm_images/images_new

TIA

Replies are listed 'Best First'.
Re: Trouble with a string
by johngg (Canon) on Dec 11, 2012 at 23:14 UTC
    @VMSHUT = `cat /tmp/virshlist_shutdown`;

    You will also need to remove the line terminator from each line of the array using chomp otherwise each file name will have a spurious line terminator at the end.

    $ cat zzz Line 1 Line 2 Line 3 $ perl -e ' > @lines = `cat zzz`; > print qq{>$_<\n} for @lines;' >Line 1 < >Line 2 < >Line 3 < $ perl -e ' > @lines = `cat zzz`; > chomp @lines; > print qq{>$_<\n} for @lines;' >Line 1< >Line 2< >Line 3< $

    I hope this is helpful.

    Cheers,

    JohnGG

      Thanks, I think it's the chomp. It's always the simple things.. And it doesn't help that I'm 10 years rusty and not the good with PERL to begin with. :)

Re: Trouble with a string
by kennethk (Abbot) on Dec 11, 2012 at 23:16 UTC
    Assuming your post's whitespace has not been mangled (you should wrap output in <code> tags to avoid that), your issue is that the results from the external call ends with a newline character. This is easily fixed with chomp:
    $OLDVMDIR = "/sunstorage_kvm_images/kvm_images/images"; #Current Dire +ctory $NEWVMDIR = "/sunstorage_kvm_images/kvm_images/images_new"; #Target ( +New) Directory $VMSFX = "\-vda\.img"; #File suffix for each file <snip> @VMSHUT = `cat /tmp/virshlist_shutdown`; chomp(@VMSHUT); foreach $VMSHUT (@VMSHUT) { $VMFILE = $OLDVMDIR . $VMSHUT . $VMSFX; print "$VMFILE $NEWVMDIR \n"; }

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: Trouble with a string
by Anonymous Monk on Dec 11, 2012 at 22:42 UTC