Avoiding eval when overloading a function

3 ビュー (過去 30 日間)
Daniel Shub
Daniel Shub 2012 年 8 月 29 日
I used eval in this answer where I was trying to overload display and it is making me feel sick. Is it possible to avoid the eval? A simple example is overloading display to prepend a string to object of class char ...
If you add the following function to a folder called @char
function display(X)
X = ['The string: ', X];
eval([inputname(1), ' = X;']);
eval(['builtin(''display'', ', inputname(1), ');']);
end
and then do
>> z = 'Hello world'
z =
The string: Hello world
I need the eval to get the variable name correct in the output. The documentation for display shows a work around where you recreate the functionality of the built-in display, but that is more distasteful to me than eval. Is it possible to overload display to do some preprocessing and then hand off the result to the built-in display without using eval
EDIT
My simplification has apparently confused people. In this question Jonathan essentially noted that
>> str = '<test TEST>'
returns
str =
TEST
but he wanted it to return
str =
<test TEST>
I suggested an answer which overloaded display in a manner analogous to my simplification above.
  1 件のコメント
Jan
Jan 2012 年 8 月 29 日
+1: My favorite question of the week, because it uses trivial commands to dig in the underground of the Matlab interpreter.

サインインしてコメントする。

回答 (2 件)

Jan
Jan 2012 年 8 月 29 日
I do not get the problem. Would this be useful:
function display(X)
Name = inputname(1);
if ~isempty(Name)
localAssignName(Name, X);
builtin('display', Name);
end
end
function localAssignName(Name, Data)
assignin('caller', Name, ['The string: ', Data]);
end
I cannot test this currently. How does the output differ from your expectations?
  3 件のコメント
Jan
Jan 2012 年 8 月 29 日
Then let me apply a subterfuge: Why on earth do you need such a strange function?!
I'll take a look into the source of DISPLAY in the evening. Obviously it uses inputname itself, such that my approach must fail. What happens with your method, when the variable is called "inputname" or "builtin"?
Daniel Shub
Daniel Shub 2012 年 8 月 29 日
The original question that I was answering, which addressed a problem that I have had in the past, is how to display a variable which contains an HTML string. The DISPLAY function is built-in so you cannot see the code. Using poorly named variables causes problems.

サインインしてコメントする。


Sean de Wolski
Sean de Wolski 2012 年 8 月 29 日
編集済み: Sean de Wolski 2012 年 8 月 29 日
Perhaps (probably) I'm missing something, but could you just use fprintf?
  1 件のコメント
Daniel Shub
Daniel Shub 2012 年 8 月 29 日
No, see this answer and the related question.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by