Checking for correct invocation of a command line haskell program

From HaskellWiki
Revision as of 13:48, 10 April 2007 by Tphyahoo (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Running our example:


   thartman@linodehaskell:~/learning/haskell/UnixTools/arghandling>./args.sh
   Checking for correct invocation of a command line / shell haskell program
     We run a nice example,
     alongside example of "ugly" argument checking that is simpler to write,
     but gives a less user friendly error message when the program is invoked incorrectly


   **********
   nice arg handling, no errors:
   "0 1 2"


   ugly arg handling, no errors:
   "0 1 2"


   nice arg handling, errors:
   *** Exception: args length does not equal 3. args: : ["0","1"]
   usage example: $ runghc arghandling-nice.hs firstarg secondarg thirdarg


   ugly arg handling, errors:
   *** Exception: user error (Pattern match failure in do expression at arghandling-ugly.hs:3:10-29)

Source code...

args.sh:


   thartman@linodehaskell:~/learning/haskell/UnixTools/arghandling>cat args.sh
   cat <<EOF
   Checking for correct invocation of a command line / shell haskell program
     We run a nice example,
     alongside example of "ugly" argument checking that is simpler to write,
     but gives a less user friendly error message when the program is invoked incorrectly


   **********
   EOF
   echo nice arg handling, no errors:
   runghc arghandling-nice.hs 0 1 2
   echo
   echo
   echo ugly arg handling, no errors:
   runghc arghandling-ugly.hs 0 1 2
   echo
   echo


   echo nice arg handling, errors:
   runghc arghandling-nice.hs 0 1
   echo
   echo
   echo ugly arg handling, errors:
   runghc arghandling-ugly.hs 0 1


   thartman@linodehaskell:~/learning/haskell/UnixTools/arghandling>cat arghandling-nice.hs
   import System
   main = do args <- getArgs
             let usagemsg = "usage example: $ runghc arghandling-nice.hs firstarg secondarg thirdarg"
             case args of
               [first,second,third] -> process first second third
               _                    -> error $ "args length does not equal 3. args: : " ++ ( show args ) ++ "\n" ++ usagemsg
   process a b c = print $ unwords [a,b,c]


   thartman@linodehaskell:~/learning/haskell/UnixTools/arghandling>cat arghandling-ugly.hs
   import System
   main = do [first,second,third] <- getArgs
             process first second third
   process a b c = print $ unwords [a,b,c]