douxueke5653 2018-01-17 10:27
浏览 155

使用sed重写代码(搜索和替换)

I have hundreds of statements like this in a codebase:

if ($stmt->execute(array(/* parameters */))) {
    $att = $stmt->fetchAll(); /* or any other fetch method */
} else {
    throw new DatabaseException(__METHOD__.": failed");
}

Another variant, which does not fetch any data:

if (!$stmt->execute(array(/* parameters */))) {
    throw new DatabaseException("Error");
}

In both cases, the if ... and throw ... should be removed, i.e. the first snippet would be reduced to:

$stmt->execute(array(/* parameters */));
$att = $stmt->fetchAll(); /* or any other fetch method */

and the second:

$stmt->execute(array(/* parameters */));

Note:

  • array(/* parameters */) may be missing if there are no parameters present.
  • $stmt may have another name (like $foo).

Background: Instead of a lot of custom code, I would like to have PDO throw an Exception when an error occurs. Currently it is set to silently ignore errors, which needs a lot of additional checks...

Note: If this is too complex for sed or similiar tools, I will accept an answer which points to another tool that could help avoid rewriting all those statements by hand.

  • 写回答

1条回答 默认 最新

  • dtpd58676 2018-01-17 12:20
    关注
    $> cat codes.txt
    
    if ($stmt->execute(array(/* parameters */))) {
      $att = $stmt->fetchAll(); /* or any other fetch method */
    } else {
      throw new DatabaseException(__METHOD__.": failed");
    }
    if (!$stmt->execute(array(/* parameters */))) {
      throw new DatabaseException("Error");
    }
    
    $> perl -p0777e 's:(if \(\s*\!?\s*)(.*?)(\s*\)\s*\{\s*)((.*?)\s*\}\s*else\s*\{\s*)?throw .*?;\s*\}:$2;
    $5:g' codes.txt
    
    $stmt->execute(array(/* parameters */));
    $att = $stmt->fetchAll(); /* or any other fetch method */
    $stmt->execute(array(/* parameters */));
    

    1. This solution is only for non-nested {} codes.
    2. For nested {}, it will be very difficult, and I do not think regexp could do. You'll need to write a sort of parser for that.
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示