如何在.t文件中加载.mhtml测试嵌入式Perl,规避文件名识别问题?
Great question! I’ve run into this exact issue when testing Mason components stored in non-file sources before—here’s how to fix it cleanly, bypassing the file-based lookup that’s causing your frustration.
核心问题分析
When you pass raw content to $interp->exec($source), Mason’s underlying load() method defaults to treating the input as a filename instead of in-memory code. The fix is to explicitly create a Mason component object from your loaded content first, then execute that object directly.
推荐解决方法:使用make_component创建内存组件
Mason’s interpreter has a built-in make_component method that accepts raw source content directly, letting you skip the file system entirely. This is the most idiomatic approach:
use HTML::Mason::Interp; use File::Slurp; # Load your .mhtml content into memory my $source = read_file('test.mhtml'); # Initialize the Mason interpreter my $interp = HTML::Mason::Interp->new(); # Create an in-memory component from your source my $component = $interp->make_component( source => $source, comp_id => 'test.mhtml', # Optional: helps with error message clarity comp_path => '/test_component', # Optional: mimics a path for dependency resolution ); # Execute the component directly $interp->exec($component);
替代方法:手动实例化Component对象
If you need more control, you can directly create an HTML::Mason::Component instance. This works well for simple use cases:
use HTML::Mason::Interp; use HTML::Mason::Component; use File::Slurp; my $source = read_file('test.mhtml'); my $interp = HTML::Mason::Interp->new(); my $component = HTML::Mason::Component->new( source => $source, name => 'test_component', # Optional: improves debug output ); $interp->exec($component);
额外提示:处理组件依赖
If your .mhtml file references other components (e.g., <& /shared/header &>), make sure to set a valid comp_root when initializing the interpreter, or specify a comp_path when creating your in-memory component. This ensures Mason can resolve relative component calls correctly.
内容的提问来源于stack exchange,提问作者David.Hodgkinson

