Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^3: Replacing an entire line if a substring is found

by victorz22 (Sexton)
on Apr 26, 2017 at 06:11 UTC ( [id://1188950]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Replacing an entire line if a substring is found
in thread Replacing an entire line if a substring is found

Thanks for the help but how would i set up that while statement to iterate through a scalar variable rather than a file handle? I have all my data stored in a scalar variable called $fileContent. So in other words how would i set up the while block using $fileContent rather than <DATA>

#This is how I read in the file my $fileContent = do { open(my $fileHandle, $inputFile) or die "Could not open file '$inp +utFile' $!"; local $/; <$fileHandle>; };

Replies are listed 'Best First'.
Re^4: Replacing an entire line if a substring is found
by huck (Prior) on Apr 26, 2017 at 06:56 UTC

    Any particular reason it be to be in a single string? an array would be much easier to process and involve less character handling while doing the replacements.

    use strict; use warnings; use feature 'say'; my @lines=<DATA>; for my $line (@lines) { chomp $line; if (index($line, 'SUBSTR') > -1 ) {$line='FOO'; } } #for my $line (@lines) { say $line; } my $fileContent=join("\n",@lines); say $fileContent; __DATA__ path/to/some/file path/to/some/other/file path/to/SUBSTR/file #replace entire line if SUBSTRING is found path/to/file

Re^4: Replacing an entire line if a substring is found
by 1nickt (Canon) on Apr 26, 2017 at 15:23 UTC

    I imagine you have seen and copied syntax like:

    my $data = do { local $/, <DATA> };
    ... which Monks use a lot around here to demonstrate solutions using data contained in the script.

    But in your case, if you are interested in handling the lines one at a time, and they exist in a separate file, there's no good reason to combine them all in a scalar.

    open my $fh, '<', $filename or die $!; while ( <$fh> ) { ... # process one line at a time }

    Hope this helps!


    The way forward always starts with a minimal test.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-24 22:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found