Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Writing to a file

by marinersk (Priest)
on May 06, 2017 at 13:41 UTC ( [id://1189665]=note: print w/replies, xml ) Need Help??


in reply to Writing to a file

Hello, victorz22. I am writing this in hopes that you actually want to get better at using Perl.

I've rewritten your script, but I had to guess at some of your intentions.

I pointedly avoided the use of modules so you could see the logic.

This is not how I would write the code. This is strictly for your learning benefit.

#!/usr/bin/perl use strict; use warnings; # Using this array to simulate the input file (reduces code size) my @Inpbuf = ( 'old/path/to/some/file', 'another/old/path/to/some/file', 'one/more/old/path/to/some/file', 'bad/cold/example/old/path/to/some/file', ); # This is the old path my $Oldpat = 'old'; # This is the desired new path my $Newpat = 'new'; # This is a horrible way to specify the directory separator (reduces c +ode size) my $Dirsep = "/"; my $Dirrgx = quotemeta $Dirsep; # Loop through the input and demonstrate two ways to perform the adjus +tment foreach my $inpbuf (@Inpbuf) { # Translation here so we can support future multiple translation l +ogic my $oldrgx = quotemeta $Oldpat; # This should produce unwanted results on fourth line of data my $tstbuf = $inpbuf; $tstbuf =~ s/$oldrgx/$Newpat/g; print " Risky transation: [$inpbuf] -> [$tstbuf]\n"; # This probably has a higher rate of intended results my @inpelt = split /$Dirrgx/, $inpbuf; my @outelt = (); foreach my $inpelt (@inpelt) { my $outelt = $inpelt; $outelt =~ s/^$oldrgx$/$Newpat/; push @outelt, $outelt; } my $outbuf = join $Dirsep, @outelt; print "Proper translation: [$inpbuf] -> [$outbuf]\n"; print "\n"; } exit; __END__

My results:

P:\>chg10.pl Risky transation: [old/path/to/some/file] -> [new/path/to/some/file +] Proper translation: [old/path/to/some/file] -> [new/path/to/some/file +] Risky transation: [another/old/path/to/some/file] -> [another/new/p +ath/to/some/file] Proper translation: [another/old/path/to/some/file] -> [another/new/p +ath/to/some/file] Risky transation: [one/more/old/path/to/some/file] -> [one/more/new +/path/to/some/file] Proper translation: [one/more/old/path/to/some/file] -> [one/more/new +/path/to/some/file] Risky transation: [bad/cold/example/old/path/to/some/file] -> [bad/ +cnew/example/new/path/to/some/file] Proper translation: [bad/cold/example/old/path/to/some/file] -> [bad/ +cold/example/new/path/to/some/file] P:\>

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1189665]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (9)
As of 2024-04-18 15:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found