Search code examples
perldivide

Perl: Why can't divide?


Why divide is not working?

echo 'cb0' | perl -p -e 's/(\w{3})/sprintf("%d", ( hex($1)/4 ))/e'

Number found where operator expected at -e line 1, near
"s/(\w{3})/sprintf("%d", ( hex($1)/4" syntax error at -e line 1, near
"s/(\w{3})/sprintf("%d", ( hex($1)/4" Execution of -e aborted due to
compilation errors.

Raw input data is 12 bits hex number.


Solution

  • The default delimiter for substitution s/// is not balanced, so you get the error. This is because you are dividing the $1 by 4 and it introduced another '/' . So to be safe use some other character other than the one that would mess with the expression. In this case better use <> as delimtier

    $ echo 'cb0' | perl -p -e 's<(\w{3})><sprintf("%d", ( hex($1)/4 ))>e '
    812
    

    when you convert s/// with other delimiters, you have to pair <...>, (...), [...] and {...}. I chose <> as it is not there in the expression.