Main do function keeps overwriting file

What I want to do –
I want to parse an error.txt file and find all the lines where dealer_login is in the string.

The code.

import Control.Monad
import Data.List

main = forever $ do
    contents <- readFile "./error.txt" 
    writeFile "dealer_login_errors.txt" (errorLogsFilter contents)

errorLogsFilter :: String -> String
errorLogsFilter input = 
    let allLines = lines input
        shortLines = filter(\line -> isInfixOf "dealer_login" line) allLines
        result =  unlines shortLines 
    in result

It is not until I close power shell that the script seems to stop writing and overwriting the file. I don’t think this is normal behavior. I could be wrong.

I would like to make the string “dealer_login” dynamic and base it on user input. If you can help with that too that would be nice.

I referenced Input and Output - Learn You a Haskell for Great Good!

1 Like

The forever function that you’re using makes the code run forever. Try to remove it. And try to use getArgs from the module System.Environment to grab the command line arguments, or use getLine if you prefer reading from the standard input. Do that in the do context and pass the result as an argument to your errorLogsFilter function.

If you need more pointers feel free to ask.

1 Like

Hey, so I figured it out.
But there is part of the syntax I don’t understand.
I made it work by writing

import Control.Monad
import Data.List

import System.Environment

main = do
        contents <- readFile "./error.txt" 
        [args] <-  getArgs
        writeFile "dealer_login_errors.txt" (errorLogsFilter contents args)

errorLogsFilter :: String -> String ->  String
errorLogsFilter input args = 
    let allLines = lines input
        shortLines = filter(\line -> isInfixOf args line) allLines
        result =  unlines shortLines 
    in result

The line [args] < - getArgs is where I have a question.

What I think its doing is taking things inside of my array to make it the type of String.

However I initially tried

args < - getArgs!!0 to get the first item of the array. This didn’t work. why ?

Forget it I just realized what I was doing wrong! Thank you. I was trying to extract a index from a function provided by haskell. That made no since as it is a function and not a list. Duh!!

1 Like