-3

I have this code working, but this is only for one file with specific name, how can I let it does all .vb file in current folder and output with file name plus _1 in the back

#!/usr/bin/perl
use strict;
use warnings;

open my $fhIn,  '<', 'file.vb'          or die $!;
open my $fhOut, '>', 'file_1.vb'        or die $!;

while (<$fhIn>) {
    print $fhOut "'01/20/2016 Added \ngpFrmPosition = Me.Location\n" if /MessageBox/ and !/'/;
    
    print $fhOut $_;
}

close $fhOut;
close $fhIn;
Peter H
  • 13
  • 3
  • 3
    `enter code here` -- nice touch. How about [readdir](http://perldoc.perl.org/functions/readdir.html)? (It doesn't look like you've put much effort into researching and/or solving this problem on your own.) – Matt Jacob Jan 20 '16 at 22:12
  • It's not clear which part you're struggling with, but [this](http://stackoverflow.com/questions/22566/how-do-i-read-in-the-contents-of-a-directory-in-perl/22573) will get you 97% of the way there. – Matt Jacob Jan 20 '16 at 22:23
  • 1
    @MattJacob: `enter code here` is what the Stack Overflow page writes if you try to mark some if your post as code without selecting anything – Borodin Jan 20 '16 at 23:31
  • @Borodin Ah, that makes sense. I obviously thought the OP was simply letting us know where we could deposit his fully working code for him. – Matt Jacob Jan 20 '16 at 23:42

1 Answers1

3

I might approach it like this. (This assumes the script is running in the same directory as the .vb files).

#!/usr/bin/perl
use strict;
use warnings;

# script running in same directory as the .vb files

for my $file (glob "*.vb") {

    my $outfile = $file =~ s/(?=\.vb$)/_1/r;
    print "$file $outfile\n"; # DEBUG 

    # open input and output files

    # do the while loop
}

The print statement in the loop is for debug purposes - to see if you are creating the new file names correctly. You can delete it or comment it out when you are satisfied you have got the files you want.

Update: Put the glob in the for loop instead of reading it to an array.

Chris Charley
  • 6,403
  • 2
  • 24
  • 26