Fisher
Fisher

Reputation: 422

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.

Upvotes: 1

Views: 136

Answers (3)

stack0114106
stack0114106

Reputation: 8791

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.

Upvotes: 4

Dave Cross
Dave Cross

Reputation: 69314

This doesn't work:

$ echo 'cb0' | perl -p -e 's/(\w{3})/sprintf("%d", ( hex($1)/4 ))/e'
Unknown regexp modifier "/4" at -e line 1, at end of line
syntax error at -e line 1, near "s/(\w{3})/sprintf("%d", ( hex($1)/4 )"
Execution of -e aborted due to compilation errors.

This does:

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

So does this, and it might be easier to follow:

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

When you use a / character as the separator character in a substitution, then all occurrences of / in your expression will be seen as separators. If you want one to be see as something else (a division operator, for example) you need to escape it (by putting \ in front of it).

Another option is to choose a different separator for your substitution. In my third example, I've switched to using | instead. In this case, the / is no longer seen as special and doesn't need to be escaped.

Upvotes: 2

drclaw
drclaw

Reputation: 2503

Either use a different delimiter for the substitution or you will need to escape the divide with a backslash:

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

Upvotes: 0

Related Questions