CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [FishMonger] How to get perl inline option working on empty files?: Edit Log



matteoguglielmi
Novice

Aug 15, 2014, 9:23 AM


Views: 7055
Re: [FishMonger] How to get perl inline option working on empty files?

... because sometimes I need to leave the file unmodified but get the actual result (whole file + new line appended) printed on the standard output (so that I can redirect it to a new file, for instance).

This is my code:


Code
printToStdOut() { 
[ "$1" ] || {
printToStdOut "USAGE: $FUNCNAME MESSAGE"
return 0
}

printf "%s\n" "$*"
}

printToStdErr() {
[ "$1" ] || {
printToStdOut "USAGE: $FUNCNAME MESSAGE"
return 0
}

printf "%s\n" "$*" >&2
}

assertVarNameIsValid() {
[ "$1" ] || {
printToStdOut "USAGE: $FUNCNAME VARNAME"
return 0
}

case $1 in
[!a-zA-Z_]*|*[!a-zA-z0-9_]*) return 1 ;;
esac
}

assertVarIsNotSet() {
[ "$1" ] || {
printToStdOut "USAGE: $FUNCNAME VARNAME"
return 0
}

assertVarNameIsValid "$1" && [ "${!1+X}" != X ]
}

assertFileExists() {
[ "$1" ] || {
printToStdOut "USAGE: $FUNCNAME FILE"
return 0
}

[ -e "$1" ] || return 1
}

assertFileIsNotEmpty() {
[ "$1" ] || {
printToStdOut "USAGE: $FUNCNAME FILE"
return 0
}

assertFileExists "$1" && [ -s "$1" ] || return 1
}


... and the appendLine function:


Code
appendLine() { 
case $# in
0|1)
printToStdOut "USAGE: [iNLINE=] $FUNCNAME LINE FILE1 [FILE2 ... FILEN]"
;;
*)
local lINE="$1" && shift
local oPTS fILE fAULT=0

assertVarIsNotSet iNLINE || oPTS='-i'

for fILE in "$@"; do
if assertFileExists "$fILE"; then
if assertFileIsNotEmpty "$fILE"; then
perl $oPTS -ple 'BEGIN {$tmp=shift(@ARGV)} if (eof) {print; $_=$tmp}' "$lINE" "$fILE"
else
assertVarIsNotSet iNLINE && echo "$lINE" || echo "$lINE" > "$fILE"
fi
else
assertVarIsNotSet iNLINE &&
{ printToStdErr "ERROR: $FUNCNAME: File \"$fILE\" does not exist."; fAULT=1; } ||
echo "$lINE" > "$fILE"
fi
done

return $fAULT
;;
esac
}



(This post was edited by matteoguglielmi on Aug 15, 2014, 9:40 AM)


Edit Log:
Post edited by matteoguglielmi (Novice) on Aug 15, 2014, 9:25 AM
Post edited by matteoguglielmi (Novice) on Aug 15, 2014, 9:27 AM
Post edited by matteoguglielmi (Novice) on Aug 15, 2014, 9:28 AM
Post edited by matteoguglielmi (Novice) on Aug 15, 2014, 9:40 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives